C Programming - Beginner to Brilliance / Control Flow Statements

Looping Statements

🚦 Why Use Loops?

Imagine this:

πŸ§β€β™‚οΈ You're told: β€œPrint the numbers from 1 to 100.”

Without loops, you'd have to write:

printf("1\\n");
printf("2\\n");
printf("3\\n");
// ...up to 100!

πŸ˜“ That's boring, long, and prone to mistakes.

πŸ‘‰ Loops allow us to repeat the same code block multiple times, efficiently and cleanly.


🧭 Types of Loops in C

C provides three types of loops:

πŸ” for Loop – Count-Controlled Loop

πŸ“Œ Syntax:

for (initialization; condition; increment/decrement) {
    // loop body
}

πŸ” Parts of a for loop:

  1. Initialization – Start value (e.g., int i = 1)

  2. Condition – Loop continues while this is true (e.g., i <= 5)

  3. Increment/Decrement – Changes the loop variable (i++ or i--)


βœ… Example:

for (int i = 1; i <= 5; i++) {
    printf("%d\\n", i);
}
1
2
3
4
5

πŸ” Example: Reverse counting

for (int i = 5; i >= 1; i--) {
    printf("%d ", i);
}
5 4 3 2 1

πŸ” while Loop – Condition-Controlled Loop

πŸ“Œ Syntax:

while (condition) {
    // loop body
}
  • Checks the condition before the first execution.

  • If condition is false initially, the loop won’t run at all.


βœ… Example:

int i = 1;
while (i <= 5) {
    printf("%d\\n", i);
    i++;
}
1
2
3
4
5

🚨 Infinite Loop Danger:

If the condition never becomes false, the loop runs forever.

while (1) {
    printf("Forever!\\n");  // Infinite loop (avoid unless intentional)
}

πŸ” do-while Loop – Exit-Controlled Loop

πŸ“Œ Syntax:

do {
    // loop body
} while (condition);
  • Runs the loop body first, then checks the condition.

  • Loop will always run at least once even if the condition is false.


βœ… Example:

int i = 1;
do {
    printf("%d\\n", i);
    i++;
} while (i <= 5)
1
2
3
4
5

❗ Real Difference from while:

int x = 10;

while (x < 5) {
    printf("Hello from while!");
}

do {
    printf("Hello from do-while!");
} while (x < 5)
Hello from do-while!

Even though the condition is false, do-while ran once.


πŸ“Œ Difference between for, while, and do-while loops in C:

Feature

for Loop

while Loop

do-while Loop

Use Case

When number of iterations is known

When condition must be checked before loop

When loop must run at least once

Syntax

for(init; cond; update)

while(condition)

do { } while(condition);

Condition Check

Before the first iteration

Before the first iteration

After the first iteration

Minimum Executions

0 times (if condition is false)

0 times

1 time minimum

Best For

Counting loops, fixed iterations

Event-driven loops, unknown iterations

Menu-driven programs, at-least-once runs

Initialization & Update

Inside loop header

Separate from loop

Update must be handled manually