C from Zero · Week 2
0% complete0 / 0 activities
Saved on this device

Week 2: Repetition, Algorithms & Functions

You already know the basic language of C. Now you will make programs repeat work, trace state changes, solve mathematical number problems, and split larger tasks into reusable functions. Every chapter follows the same learning cycle: Introduction → When & Why → Example → Run it → Enter your observed output → Unlock detailed explanation → Activities → Practice Set → Project.

8chapters
56activities
16runnable examples
30assessment questions
01

Repetition & the while Loop

Understand why loops exist before learning to type their syntax.

1. Introduction

A loop is a control structure that repeats a block of code while a condition remains true. This matters because computers are excellent at doing the same precise operation thousands or millions of times. Instead of writing the same instruction again and again, you describe the repetition rule once.

2. When & Why

Use a loop when the same task must happen repeatedly: counting, processing a sequence, validating input, accumulating a result, or examining the digits of a number.

The four things to identify: starting state → condition → repeated body → update toward termination.

3. Example

while_01.coutput hidden
Flexible: line breaks and extra spaces are ignored.

4. Example code explanation — after you run it

The explanation unlocks only after you enter the actual output. It covers symbols such as while, the condition, i++, printf, %d, \n, braces and return 0;.

5. Use Cases

  • Count until a limit
  • Read values until a sentinel such as 0
  • Validate input repeatedly
  • Process digits one by one

6. Activities

Practice Set:
  1. Print 1–20
  2. Print 20–1
  3. Print multiples of 3 below 50
  4. Print first 10 squares
  5. Find 1+2+...+n
  6. Count even values from 1 to n
  7. Write a loop whose stopping condition depends on user input
Project: Number Sequence Generator — input a start and end value, print the sequence forward and backward.
02

while in Depth

Execution order, boundaries, sentinel values, and infinite loops.

1. Introduction

while checks its condition before every repetition. Therefore the body may execute zero times. That small fact becomes very important when writing validation and input-driven programs.

2. When & Why

Choose while when you can naturally say “keep doing this while this condition is true,” especially when the number of repetitions is not known in advance.

3. Example

while_02.coutput hidden
Flexible: line breaks and extra spaces are ignored.

4. Example — sentinel pattern

while_03.c
Flexible: line breaks and extra spaces are ignored.
Typical bugs: forgetting the update creates an infinite loop; choosing the wrong boundary creates an off-by-one error.

5. Use Cases

  • Input until a sentinel value
  • Running totals
  • Running maximum/minimum
  • Repeated validation

6. Activities

Practice Set:
  1. Count to 100
  2. Print multiples of 5
  3. Count down from user input
  4. Sum 1 to n
  5. Read values until 0 and count them
  6. Track the maximum value
  7. Create and repair an infinite loop
Project: Basic Statistics Counter — read integers until 0 and report count, positive count, negative count and sum.
03

The for Loop

A compact loop form for counter-controlled repetition.

1. Introduction

A for loop puts initialization, condition and update together. It often makes a known repetition count easy to read.

2. When & Why

Use it when you naturally think “start here, continue while this is true, change the counter this way.”

3. Anatomy

for(initialization; condition; update)
{
    // repeated body
}
initialization
sets the starting state
condition
allows or stops the next iteration
update
moves the counter toward termination
body
the work repeated each iteration

4. Example

for_01.c
Flexible: line breaks and extra spaces are ignored.

5. Example — accumulator

for_02.c
Flexible: line breaks and extra spaces are ignored.

6. Use Cases

  • Tables
  • Known iteration counts
  • Series and sums
  • Counting problems

7. Activities

Practice Set:
  1. Print 1–10
  2. Even numbers 2–50
  3. Odd numbers 1–49
  4. Multiplication table
  5. Factorial
  6. Sum of squares
  7. Rewrite a while solution using for and compare readability
Project: Multiplication Table Generator — user chooses the number and limit.
04

do...while

Run once first, then decide whether to repeat.

1. Introduction

A do...while checks its condition after the body. Consequently, the body executes at least once.

2. When & Why

This makes it useful for menus, retry prompts and input that must be requested before you can know whether another attempt is necessary.

3. Example

do_01.c
Flexible: line breaks and extra spaces are ignored.

4. Example — menu pattern

do_02.c
Flexible: line breaks and extra spaces are ignored.

5. Use Cases

  • Menus
  • Retry systems
  • Validation
  • “Ask at least once” interactions

6. Activities

Practice Set:
  1. Write a do...while that runs once with a false condition
  2. Ask until a positive number is entered
  3. Build a 1/0 menu
  4. Ask until a target number is entered
  5. Convert a while program
  6. Compare while vs do...while with a false first condition
  7. Explain why menus often fit do...while
Project: Interactive Calculator Menu that repeats until Exit.
05

Nested Loops

Think in rows and columns; one loop can control repeated work inside another.

1. Introduction

A nested loop is a loop inside another loop. The outer loop can represent rows or larger units; the inner loop can represent repeated work inside each row.

2. When & Why

Use nested loops for grids, patterns, tables and problems with two dimensions of repetition.

3. Example

nested_01.c
Flexible: line breaks and extra spaces are ignored.

4. Example — multiplication grid

nested_02.c
Flexible: line breaks and extra spaces are ignored.

5. Use Cases

  • Patterns
  • Tables
  • Grid-like data
  • All pair combinations

6. Activities

Practice Set:
  1. 3×5 star rectangle
  2. 4×4 number square
  3. Increasing triangle
  4. Decreasing triangle
  5. Print row/column coordinates
  6. 5×5 multiplication grid
  7. Predict total inner-loop executions before running
Project: Pattern Generator — build at least three distinct patterns and one of your own.
06

Number Logic with Loops

Connect mathematics, integer arithmetic and repetition.

1. Introduction

One of the best ways to learn loops is to use them for digit algorithms. Two very useful integer operations are n % 10 to obtain the last digit and n / 10 to remove the last digit when using integer arithmetic.

2. When & Why

This pattern lets one loop process every digit of a positive integer. It is the basis of digit sum, digit count, reversal and palindrome problems.

n % 10
last digit
n / 10
remove last digit
accumulator
a variable that builds a result over iterations
dry run
trace the state on paper before executing

3. Example — digit sum

number_01.c
Flexible: line breaks and extra spaces are ignored.

4. Example — reverse

number_02.c
Flexible: line breaks and extra spaces are ignored.

5. Use Cases

  • Digit count
  • Digit sum/product
  • Reverse
  • Palindrome
  • Largest/smallest digit
  • Even/odd digit counts

6. Activities

Practice Set:
  1. Count digits
  2. Sum digits
  3. Product digits
  4. Reverse
  5. Palindrome
  6. Largest digit
  7. Count even and odd digits
Project: Number Analyzer — return multiple facts about one integer.
07

Functions

Move from “one long main” to reusable, named pieces of logic.

1. Introduction

A function packages a task into a named unit. This reduces duplication and lets you reason about a big problem as smaller problems. Functions are a foundation of modular programming.

2. When & Why

Use a function when a task is logically separate, repeated, or easier to test when given a name.

TermMeaning
DefinitionThe function's code.
CallRequests that the function execute.
ParameterNamed input in the function definition.
ArgumentActual value passed in a call.
Return valueValue sent back to the caller.

3. Example — no parameters, no return value

function_01.c
Flexible: line breaks and extra spaces are ignored.

4. Example — parameters and return value

function_02.c
Flexible: line breaks and extra spaces are ignored.

5. Use Cases

  • Reusable calculations
  • Validation helpers
  • Readable program structure
  • Testing one task at a time

6. Activities

Practice Set:
  1. Create a no-parameter function
  2. Call it multiple times
  3. Function with one parameter
  4. Function with two parameters
  5. Function that returns a value
  6. Arithmetic function set
  7. Refactor an old program into functions
Project: Modular Calculator — add, subtract, multiply, divide plus a clean main().
08

Integration & Real Problem Solving

Combine loops, conditions and functions without turning main into a mess.

1. Introduction

Programming becomes useful when concepts work together. A menu can use a loop; its choices can use conditions; calculations can be delegated to functions; repeated input can use a loop; testing can verify each operation.

2. When & Why

Use decomposition when a problem contains multiple distinct tasks. Before coding, identify inputs, outputs, subtasks, loop points and decision points.

3. Example architecture

main()
 ├── showMenu()
 ├── add(...)
 ├── factorial(...)
 ├── reverseNumber(...)
 └── isEven(...)

4. Example — loop + function + condition

integration_01.c
Flexible: line breaks and extra spaces are ignored.

5. Activities

Practice Set:
  1. Write a menu-driven calculator
  2. Make each operation a function
  3. Use a loop for repeated menu choices
  4. Add even/odd and factorial utilities
  5. Add reverse and palindrome utilities
  6. Create a test plan with normal and edge cases
  7. Debug one intentionally broken version
Week 2 Capstone: C Utility Toolkit — a menu-driven program containing several utilities, organized with functions and repeated with a suitable loop.
Q

Final Combined Week 2 Quiz

Tests concepts, output prediction, tracing, debugging, loop choice, functions, and problem solving.

Do the output questions without running the code first. Then use your compiler afterward to verify your reasoning.

C from Zero · Week 2 · Local progress is stored only in this browser.