C
Loops & Iteration in C
🏠 Home Lecture 12: Loops in C
Iterative Control Flow

Loops in C Programming

Loops allow a program to repeat a sequence of instructions multiple times based on a condition, eliminating code duplication and automating complex calculations.

Suppose you need to print numbers 1 to 100. What is the main advantage of using a loop?
loop_intro.cSequential vs Loop
#include <stdio.h> int main(void) { // Without loop: Copy-pasting 5 times printf("Count: 1\n"); printf("Count: 2\n"); // With a Loop: Clean & Dynamic int count = 1; while (count <= 5) { printf("Count: %d\n", count); count++; // Update counter } return 0; }
1

Initialization

Set starting value for counter variable (e.g., i = 1).

2

Condition

Test expression evaluated before/after each cycle (e.g., i <= 5).

3

Body

The block of statements executed repeatedly while condition is true.

4

Update Step

Increments or decrements counter to ensure eventual loop termination.

Entry-Controlled Loop

The while Loop Tracer

The while loop checks its test condition before executing the loop body. If the condition is false initially, the body does not execute even once.

Interactive Execution Step Visualizer

Adjust inputs and step through the loop execution line by line.

Output Terminal:
Click "Next Step ▶" to begin execution...
Current Variable: i = 1 | Condition (i <= 4): Pending
while_demo.cActive Execution Line
int i = 1; while (i <= 4) { printf("i = %d\n", i); i++; } printf("Loop Finished!\n");
Exit-Controlled Loop

The do-while Loop Tracer

Unlike while, the do-while loop tests its condition at the bottom. This guarantees that the loop body executes at least once, regardless of the initial condition.

Interactive Execution Step Visualizer

Notice how the body executes FIRST before checking condition at line 5!

Output Terminal:
Click "Next Step ▶" to begin execution...
Current Variable: i = 1 | Condition (i <= 4): Pending
dowhile_demo.cActive Execution Line
int i = 1; do { printf("i = %d\n", i); i++; } while (i <= 4); printf("Loop Finished!\n");
Structured Iteration

The for Loop Tracer

The for loop consolidates Initialization, Condition, and Update into a single compact header line. Step through to watch the exact order of execution!

Interactive Header Step Visualizer

Observe: 1. Init (once) ➔ 2. Condition Check ➔ 3. Body ➔ 4. Update

Output Terminal:
Click "Next Step ▶" to begin execution...
Current Variable: i = 1 | Condition (i <= 4): Pending
for_demo.cHeader Sub-Part Execution
for ( int i = 1 ; i <= 4 ; i++ ) { printf("i = %d\n", i); } printf("Loop Finished!\n");
Deep Intuition Sandbox

Off-By-One Sandbox & Boundary Intuition

Off-by-one errors (OBOE) are the #1 source of array index bugs. Use this tactile lab to predict first, then step/run!

Predict & Test Sandbox

🎯 Predict Before Running:
Enter predictions above and click "Run Sandbox" or "Step ▶".

Visual Cell Traversal & Outcome

for (int i = 0; i < 5; i += 1) { visit_cell(i); }
Cell Array Memory Layout:
Actual Iteration Count: —
Last Value of i inside loop: —
Final Value of i after loop exits: —
Language Mechanics

Pre-Increment (++i) vs. Post-Increment (i++)

Understanding the exact execution timing of side effects in expressions and loop headers.

Microscope Step Visualizer

Select an operation and click "Next Step ▶" to step through execution line-by-line:

Click "Next Step ▶" to inspect variable values line-by-line...
increment_microscope.cActive Line Tracer
Loop Control Statements

break vs. continue

Jump statements allow you to bypass normal loop execution logic dynamically inside loop bodies.

Interactive Statement Test

Select control mode to see how iterations behave when encountering number 3:

Execution Terminal:
jump_control.cCode Preview
for (int i = 1; i <= 5; i++) { printf("i = %d\n", i); }
Multi-Dimensional Iteration

Nested Loops & 2D Execution Grid

Watch outer loop i hold constant while inner loop j completes its entire iteration cycle step-by-step.

Interactive 2D Matrix Controls

Loop Execution Log:
Click "Next Step ▶" to begin 2D matrix iteration...
Outer Loop i: 0 | Inner Loop j: 0
nested_demo.cCode Tracer
for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { printf("(%d,%d)", i, j); } printf("\n"); }

2D Grid Matrix Output

Verification & Debugging

Loop Invariants & Common Pitfalls

Understand formal loop correctness properties and avoid common production bugs.

💡 Loop Invariant Property

A logical condition that holds true before entering, during every iteration, and after loop termination.

// Invariant: sum = 1 + 2 + ... + i int sum = 0; for (int i = 1; i <= n; i++) { sum += i; // Invariant maintained! }

1. Infinite Loop Trap

Forgetting to update counter or writing wrong condition.

int i = 1; while (i <= 5) { printf("%d", i); // BUG: Forgot i++; }

2. Accidental Semicolon Bug

Putting a semicolon right after loop condition creates a null loop.

while (i < 5); { // Executes ONCE after empty loop ends! }

3. Floating Point Counters

Avoid using float counters due to precision issues.

// DANGER: 0.1 precision rounding error! for (float f = 0.0; f != 1.0; f += 0.1)
Question 1 of 5
Loading quiz...