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.
Repetition & the while Loop
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.
3. Example
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
- Print 1–20
- Print 20–1
- Print multiples of 3 below 50
- Print first 10 squares
- Find 1+2+...+n
- Count even values from 1 to n
- Write a loop whose stopping condition depends on user input
while in Depth
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
4. Example — sentinel pattern
5. Use Cases
- Input until a sentinel value
- Running totals
- Running maximum/minimum
- Repeated validation
6. Activities
- Count to 100
- Print multiples of 5
- Count down from user input
- Sum 1 to n
- Read values until 0 and count them
- Track the maximum value
- Create and repair an infinite loop
The for Loop
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
}sets the starting state
allows or stops the next iteration
moves the counter toward termination
the work repeated each iteration
4. Example
5. Example — accumulator
6. Use Cases
- Tables
- Known iteration counts
- Series and sums
- Counting problems
7. Activities
- Print 1–10
- Even numbers 2–50
- Odd numbers 1–49
- Multiplication table
- Factorial
- Sum of squares
- Rewrite a while solution using for and compare readability
do...while
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
4. Example — menu pattern
5. Use Cases
- Menus
- Retry systems
- Validation
- “Ask at least once” interactions
6. Activities
- Write a do...while that runs once with a false condition
- Ask until a positive number is entered
- Build a 1/0 menu
- Ask until a target number is entered
- Convert a while program
- Compare while vs do...while with a false first condition
- Explain why menus often fit do...while
Nested Loops
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
4. Example — multiplication grid
5. Use Cases
- Patterns
- Tables
- Grid-like data
- All pair combinations
6. Activities
- 3×5 star rectangle
- 4×4 number square
- Increasing triangle
- Decreasing triangle
- Print row/column coordinates
- 5×5 multiplication grid
- Predict total inner-loop executions before running
Number Logic with Loops
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.
last digit
remove last digit
a variable that builds a result over iterations
trace the state on paper before executing
3. Example — digit sum
4. Example — reverse
5. Use Cases
- Digit count
- Digit sum/product
- Reverse
- Palindrome
- Largest/smallest digit
- Even/odd digit counts
6. Activities
- Count digits
- Sum digits
- Product digits
- Reverse
- Palindrome
- Largest digit
- Count even and odd digits
Functions
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.
| Term | Meaning |
|---|---|
| Definition | The function's code. |
| Call | Requests that the function execute. |
| Parameter | Named input in the function definition. |
| Argument | Actual value passed in a call. |
| Return value | Value sent back to the caller. |
3. Example — no parameters, no return value
4. Example — parameters and return value
5. Use Cases
- Reusable calculations
- Validation helpers
- Readable program structure
- Testing one task at a time
6. Activities
- Create a no-parameter function
- Call it multiple times
- Function with one parameter
- Function with two parameters
- Function that returns a value
- Arithmetic function set
- Refactor an old program into functions
add, subtract, multiply, divide plus a clean main().Integration & Real Problem Solving
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
5. Activities
- Write a menu-driven calculator
- Make each operation a function
- Use a loop for repeated menu choices
- Add even/odd and factorial utilities
- Add reverse and palindrome utilities
- Create a test plan with normal and edge cases
- Debug one intentionally broken version
Final Combined Week 2 Quiz
Do the output questions without running the code first. Then use your compiler afterward to verify your reasoning.