GCGY Beta v1.0.1
GrowCodeEngineering
← Back to Hub
Back to Topics
c / c-control-flow
15 mins

C Level 2: Branching & Loop Iteration

Why This Matters: Control structures allow programs to make decisions and repeat execution blocks efficiently.
## Branching & Loop Mechanics

Program flow determines which statements execute based on boolean conditions.

### Loop Constructs
- `for(init; condition; update)`: Best for known iteration counts.
- `while(condition)`: Pre-condition check iteration.
- `do ... while(condition)`: Guarantees at least 1 execution pass.
MENTAL MODEL & MEMORY LAYOUT
[ Loop Start ] ──► [ Check Condition ] ──(True)──► [ Execute Block ]
                              │                            │
                           (False)                         │
                              ▼                            ▼
                        [ Exit Loop ] ◄─────────────────[ Update ]
COMMON PITFALLS TO AVOID
  • Infinite loop caused by forgetting loop index increment (i++).
  • Off-by-one errors (using `<` when `<=` is required).
For Loop Accumulator
#include <stdio.h>

int main() {
    int sum = 0;
    for(int i = 1; i <= 5; i++) {
        sum += i;
    }
    printf("Sum 1..5: %d\n", sum);
    return 0;
}

Iterates i from 1 to 5, accumulating total sum.

CONCEPT MASTERY CHECKPOINT

Which loop construct guarantees the body will execute AT LEAST ONCE?

NEXT RECOMMENDED LESSON
C Level 3: Functions & Scope
Continue Path
Challenge: Write a for loop in C that computes and prints the sum of numbers from 1 to 5.
C Level 2: Branching & Loop Iteration
1
2
3
4
5
6
7
8
9
10
11
12
13
No test case execution results available yet. Click "Run Code" to evaluate your solution.