Chapter 11Beginner

Loops in C

Repeat actions automatically! Master for, while, and do-while loops. Learn which loop to use when, and how to control loops with break and continue.

20 min readUpdated 2024-12-16
for loopwhile loopdo-whilebreakcontinuenested loopsinfinite loop

What You Will Learn

  • Use for loops when you know the count
  • Use while loops when you have a condition
  • Use do-while when you need at least one execution
  • Control loops with break and continue

01Why Do We Need Loops?

Loops allow you to execute a block of code repeatedly. Without loops, you'd have to write the same code multiple times:

❌ Without Loop (Repetitive)

printf("Hello\n");
printf("Hello\n");
printf("Hello\n");
printf("Hello\n");
printf("Hello\n");

✅ With Loop (Clean)

for (int i = 0; i < 5; i++) {
    printf("Hello\n");
}

C Provides Three Types of Loops

Loop TypeCondition CheckGuaranteed RunsBest For
whileBefore (Entry-controlled)0 timesUnknown iterations
forBefore (Entry-controlled)0 timesKnown iterations, counting
do-whileAfter (Exit-controlled)1 timeMust run at least once

02Loop Conditions

Every loop depends on a condition that determines when the loop should stop.

💡 Quick Reminder: True and False in C

In C: 0 = FALSE (loop exits) and any non-zero = TRUE (loop continues).

For detailed explanation, see Control Flow Tutorial.

Common Loop Conditions

ExpressionValueResultLoop Behavior
00FALSELoop doesn't run / exits
11TRUELoop runs / continues
-5-5 (non-zero)TRUELoop runs / continues
100100 (non-zero)TRUELoop runs / continues
5 > 31TRUELoop runs / continues
5 < 30FALSELoop doesn't run / exits
'\0' (null char)0FALSELoop doesn't run / exits
NULL pointer0FALSELoop doesn't run / exits

📝 This program demonstrates how C interprets different values as true or false in loop conditions.

true_false_demo.c
C
1#include <stdio.h>
2
3int main() {
4 // Demonstrating true/false values
5 printf("Testing loop conditions:\n\n");
6
7 // while(0) - FALSE, never runs
8 printf("while(0): ");
9 while (0) {
10 printf("This never prints");
11 }
12 printf("Skipped (0 is FALSE)\n");
13
14 // while(1) runs once with break
15 printf("while(1): ");
16 while (1) {
17 printf("Runs! (1 is TRUE)\n");
18 break;
19 }
20
21 // Negative numbers are TRUE
22 int x = -5;
23 printf("while(-5): ");
24 while (x) {
25 printf("Runs! (-5 is TRUE, non-zero)\n");
26 break;
27 }
28
29 // Comparison results
30 printf("\nComparison expressions:\n");
31 printf("5 > 3 evaluates to: %d (TRUE)\n", 5 > 3);
32 printf("5 < 3 evaluates to: %d (FALSE)\n", 5 < 3);
33 printf("5 == 5 evaluates to: %d (TRUE)\n", 5 == 5);
34
35 return 0;
36}
Output

Testing loop conditions:

while(0): Skipped (0 is FALSE)

while(1): Runs! (1 is TRUE)

while(-5): Runs! (-5 is TRUE, non-zero)

Comparison expressions:

5 > 3 evaluates to: 1 (TRUE)

5 < 3 evaluates to: 0 (FALSE)

5 == 5 evaluates to: 1 (TRUE)

💡 Common Idiom: while(1) for Infinite Loops

Since any non-zero value is true, while(1) creates an infinite loop. Use break to exit when needed.

03While Loop (Entry-Controlled)

The while loop checks the condition before each iteration. If the condition is false initially, the loop body never executes.

Syntax & Flow

while (condition) {
    // code to repeat
    // update loop variable!
}

Flow:

Check → Execute → Repeat

↑ If condition TRUE

When to Use While Loop

✅ Use While When❌ Don't Use When
Number of iterations is unknownYou know exact count beforehand
Loop depends on user inputSimple counting from A to B
Reading until end of fileIterating through array indices
Waiting for a condition to changeLoop must run at least once

📝 This program uses a while loop to sum numbers until the user enters 0.

while_sum.c
C
1#include <stdio.h>
2
3int main() {
4 int num, sum = 0;
5
6 printf("Enter numbers to sum (0 to stop):\n");
7
8 printf("Enter number: ");
9 scanf("%d", &num);
10
11 while (num != 0) { // Continue until 0 is entered
12 sum += num;
13 printf("Running sum: %d\n", sum);
14 printf("Enter number: ");
15 scanf("%d", &num);
16 }
17
18 printf("\nFinal sum: %d\n", sum);
19
20 return 0;
21}
Output (Sample Run)

Enter numbers to sum (0 to stop):

Enter number: 5

Running sum: 5

Enter number: 10

Running sum: 15

Enter number: 3

Running sum: 18

Enter number: 0

Final sum: 18

⚠️ Infinite Loop Danger

Always update your loop variable inside the loop! Forgetting to do so creates an infinite loopthat never ends.

int i = 1;
while (i <= 5) {
    printf("%d ", i);
    // MISSING: i++;  ← Loop never ends!
}

04For Loop (The Counter Loop)

The for loop is the most commonly used loop. It puts initialization, condition, and update all in one line, making it perfect for counting.

Syntax Breakdown

for (initialization; condition; update) {}
PartWhen It RunsExample
InitializationOnce, at the startint i = 0
ConditionBefore each iterationi < 5
UpdateAfter each iterationi++

Execution Order (Step by Step)

1. Initialization: int i = 0

2. Check condition: i < 3 → 0 < 3 = TRUE

3. Execute body: printf(i) → prints 0

4. Update: i++ → i becomes 1

5. Check condition: i < 3 → 1 < 3 = TRUE

... (continues until i = 3, then 3 < 3 = FALSE, loop ends)

When to Use For Loop

✅ Use For When❌ Don't Use When
You know exact number of iterationsIterations depend on runtime input
Counting from A to BWaiting for external condition
Iterating through array elementsComplex state-based loops
Nested counting (2D arrays, patterns)Loop must run at least once

📝 This program demonstrates common for loop patterns: counting up, counting down, and skipping values.

for_patterns.c
C
1#include <stdio.h>
2
3int main() {
4 // Pattern 1: Count up (0 to 4)
5 printf("Count up: ");
6 for (int i = 0; i < 5; i++) {
7 printf("%d ", i);
8 }
9 printf("\n");
10
11 // Pattern 2: Count down (5 to 1)
12 printf("Count down: ");
13 for (int i = 5; i >= 1; i--) {
14 printf("%d ", i);
15 }
16 printf("\n");
17
18 // Pattern 3: Skip values (even numbers)
19 printf("Even numbers: ");
20 for (int i = 0; i <= 10; i += 2) {
21 printf("%d ", i);
22 }
23 printf("\n");
24
25 // Pattern 4: Multiple variables
26 printf("Two counters: ");
27 for (int i = 0, j = 10; i < j; i++, j--) {
28 printf("(%d,%d) ", i, j);
29 }
30 printf("\n");
31
32 return 0;
33}
Output

Count up: 0 1 2 3 4

Count down: 5 4 3 2 1

Even numbers: 0 2 4 6 8 10

Two counters: (0,10) (1,9) (2,8) (3,7) (4,6)

05Nested Loops

A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.

Total Iterations = Outer × Inner

If outer loop runs 3 times

and inner loop runs 4 times

Total = 3 × 4 = 12 inner iterations

📝 This program prints a multiplication table using nested loops.

multiplication_table.c
C
1#include <stdio.h>
2
3int main() {
4 printf("Multiplication Table (1-5):\n\n");
5
6 // Print header row
7 printf(" ");
8 for (int j = 1; j <= 5; j++) {
9 printf("%4d", j);
10 }
11 printf("\n --------------------\n");
12
13 // Outer loop: rows (1 to 5)
14 for (int i = 1; i <= 5; i++) {
15 printf("%d | ", i);
16
17 // Inner loop: columns (1 to 5)
18 for (int j = 1; j <= 5; j++) {
19 printf("%4d", i * j);
20 }
21 printf("\n");
22 }
23
24 return 0;
25}
Output

Multiplication Table (1-5):

1 2 3 4 5

--------------------

1 | 1 2 3 4 5

2 | 2 4 6 8 10

3 | 3 6 9 12 15

4 | 4 8 12 16 20

5 | 5 10 15 20 25

📝 This program creates a triangle pattern using nested loops.

triangle_pattern.c
C
1#include <stdio.h>
2
3int main() {
4 int rows = 5;
5
6 printf("Right Triangle Pattern:\n");
7
8 for (int i = 1; i <= rows; i++) {
9 // Inner loop runs 'i' times each row
10 for (int j = 1; j <= i; j++) {
11 printf("* ");
12 }
13 printf("\n");
14 }
15
16 return 0;
17}
Output

Right Triangle Pattern:

*

* *

* * *

* * * *

* * * * *

06Do-While Loop (Exit-Controlled)

The do-while loop checks the condition after each iteration. This guarantees the loop body runs at least once, even if the condition is initially false.

Syntax & Flow

do {
    // code runs at least once
} while (condition);  // ← Semicolon!

Flow:

Execute → Check → Repeat

↑ If condition TRUE

When to Use Do-While Loop

✅ Use Do-While When❌ Don't Use When
Loop must execute at least onceYou might not need any iterations
Menu systems (show menu first)Simple counting tasks
Input validation (get input, then check)Iterating through arrays
Game loops (play, then ask continue?)Reading files that might be empty

📝 This program validates user input using do-while - keeps asking until valid input is received.

input_validation.c
C
1#include <stdio.h>
2
3int main() {
4 int age;
5
6 // Input validation with do-while
7 do {
8 printf("Enter your age (1-120): ");
9 scanf("%d", &age);
10
11 if (age < 1 || age > 120) {
12 printf("Invalid age! Please try again.\n");
13 }
14 } while (age < 1 || age > 120);
15
16 printf("\nValid age entered: %d\n", age);
17
18 if (age >= 18) {
19 printf("You are an adult.\n");
20 } else {
21 printf("You are a minor.\n");
22 }
23
24 return 0;
25}
Output (Sample Run)

Enter your age (1-120): -5

Invalid age! Please try again.

Enter your age (1-120): 150

Invalid age! Please try again.

Enter your age (1-120): 25

Valid age entered: 25

You are an adult.

While vs Do-While Comparison

while (condition FALSE)

int x = 10;
while (x < 5) {
    printf("Hi");
}
// Prints: NOTHING

do-while (condition FALSE)

int x = 10;
do {
    printf("Hi");
} while (x < 5);
// Prints: Hi (once)

07Break, Continue, and Goto

These jump statements give you control over loop execution flow.

StatementEffectCommon Use
breakExit loop immediatelyFound what you need, stop searching
continueSkip to next iterationSkip unwanted items, keep looping
gotoJump to labeled statementAvoid! (breaks out of nested loops)

📝 This program demonstrates break (finding a number) and continue (skipping values).

break_continue.c
C
1#include <stdio.h>
2
3int main() {
4 // BREAK: Exit loop when target found
5 printf("Finding first multiple of 7 (1-20):\n");
6 for (int i = 1; i <= 20; i++) {
7 if (i % 7 == 0) {
8 printf("Found: %d\n", i);
9 break; // Stop searching
10 }
11 printf("%d ", i);
12 }
13
14 // CONTINUE: Skip certain values
15 printf("\nOdd numbers from 1-10:\n");
16 for (int i = 1; i <= 10; i++) {
17 if (i % 2 == 0) {
18 continue; // Skip even numbers
19 }
20 printf("%d ", i);
21 }
22 printf("\n");
23
24 return 0;
25}
Output

Finding first multiple of 7 (1-20):

1 2 3 4 5 6 Found: 7

Odd numbers from 1-10:

1 3 5 7 9

⚠️ About goto

goto jumps to a labeled statement. It's considered bad practice because it creates "spaghetti code" that's hard to follow. See Control Flow Tutorial for more details.

📝 Acceptable use of goto: breaking out of multiple nested loops at once.

goto_nested.c
C
1#include <stdio.h>
2
3int main() {
4 // Finding coordinates in a 2D search
5 printf("Searching for (2,2) in 4x4 grid:\n");
6
7 for (int i = 0; i < 4; i++) {
8 for (int j = 0; j < 4; j++) {
9 printf("Checking (%d,%d)\n", i, j);
10 if (i == 2 && j == 2) {
11 printf(">>> FOUND! <<<\n");
12 goto found; // Exit BOTH loops
13 }
14 }
15 }
16 printf("Not found.\n");
17 goto end;
18
19 found:
20 printf("Search complete - target located.\n");
21
22 end:
23 return 0;
24}
Output

Searching for (2,2) in 4x4 grid:

Checking (0,0)

... (continues through grid)

Checking (2,1)

Checking (2,2)

>>> FOUND! <<<

Search complete - target located.

08Infinite Loops

Sometimes you intentionally create a loop that runs forever. Use break to exit when a condition is met.

Common Infinite Loop Patterns

while(1)

Most common

for(;;)

Empty for loop

while(true)

With stdbool.h

📝 This program implements a simple calculator menu using an infinite loop.

calculator.c
C
1#include <stdio.h>
2
3int main() {
4 int choice, a, b;
5
6 while (1) { // Infinite loop
7 printf("\n=== Calculator ===\n");
8 printf("1. Add\n");
9 printf("2. Subtract\n");
10 printf("3. Multiply\n");
11 printf("4. Exit\n");
12 printf("Choice: ");
13 scanf("%d", &choice);
14
15 if (choice == 4) {
16 printf("Goodbye!\n");
17 break; // Exit infinite loop
18 }
19
20 if (choice < 1 || choice > 4) {
21 printf("Invalid choice!\n");
22 continue; // Skip to next iteration
23 }
24
25 printf("Enter two numbers: ");
26 scanf("%d %d", &a, &b);
27
28 switch (choice) {
29 case 1: printf("Result: %d\n", a + b); break;
30 case 2: printf("Result: %d\n", a - b); break;
31 case 3: printf("Result: %d\n", a * b); break;
32 }
33 }
34
35 return 0;
36}
Output (Sample Run)

=== Calculator ===

1. Add

2. Subtract

3. Multiply

4. Exit

Choice: 1

Enter two numbers: 10 5

Result: 15

... (menu repeats)

09Choosing the Right Loop

Use this decision guide to pick the best loop for your situation:

🎯 Loop Selection Flowchart

Q1:Do you know exactly how many times to loop?
Yes →for(best for counting)
No →Continue to Q2
Q2:Must the loop run at least once?
Yes →do-while(menus, input validation)
No →while(may run 0 times)
ScenarioBest LoopWhy
Print numbers 1 to 100forKnown count, simple increment
Iterate through arrayforArray size is known
Read until end of filewhileUnknown iterations, file may be empty
Sum numbers until user enters 0whileUnknown how many numbers
Menu systemdo-whileMust show menu at least once
Validate user inputdo-whileGet input first, then validate
Game loopwhile(1) + breakRuns until player quits
2D pattern / matrixnested forRows and columns both known

10Common Loop Mistakes

❌ Infinite loop - forgetting to update loop variable

The most common loop bug! If the condition never becomes false, the loop runs forever.

main.c
C
// WRONG - i never changes, loops forever!
int i = 0;
while (i < 5) {
printf("%d\n", i);
// Missing i++;
}
// CORRECT
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++; // Update the loop variable!
}

❌ Off-by-one error

Looping one too many or one too few times. Check your boundaries!

main.c
C
int arr[5] = {1, 2, 3, 4, 5};
// WRONG - accesses arr[5] which doesn't exist!
for (int i = 0; i <= 5; i++) { // Should be i < 5
printf("%d ", arr[i]);
}
// CORRECT - array indices 0 to 4
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

❌ Semicolon after for/while

A semicolon creates an empty loop body!

main.c
C
// WRONG - semicolon makes loop body empty
for (int i = 0; i < 5; i++); // Loop does nothing
{
printf("%d\n", i); // Only runs once, i = 5
}
// CORRECT
for (int i = 0; i < 5; i++) { // No semicolon!
printf("%d\n", i);
}

❌ Modifying loop variable inside loop

Changing the loop counter inside the loop body causes unpredictable behavior.

main.c
C
// WRONG - modifying i inside loop
for (int i = 0; i < 10; i++) {
printf("%d ", i);
if (i == 5) {
i = 8; // Skips 6, 7 - confusing!
}
}
// BETTER - use continue or break for control
for (int i = 0; i < 10; i++) {
if (i >= 6 && i <= 7) {
continue; // Skip 6 and 7 clearly
}
printf("%d ", i);
}

❌ Using = instead of == in condition

Assignment in condition causes unexpected behavior!

main.c
C
int x = 0;
// WRONG - assigns 1 to x, always true!
while (x = 1) { // Should be x == 1
printf("Infinite loop!\n");
}
// CORRECT
while (x == 1) {
printf("x is 1\n");
}

❌ Wrong loop type for the task

Using while when you need do-while, or for when while is clearer.

main.c
C
// WRONG - duplicated code to show menu first
printf("Menu...\n");
scanf("%d", &choice);
while (choice != 0) {
process(choice);
printf("Menu...\n"); // Duplicated!
scanf("%d", &choice);
}
// CORRECT - do-while shows menu at least once
do {
printf("Menu...\n");
scanf("%d", &choice);
if (choice != 0) process(choice);
} while (choice != 0);

❌ Missing semicolon after do-while

Unlike for and while, do-while requires a semicolon at the end!

main.c
C
// WRONG - missing semicolon
do {
printf("Hello\n");
} while (condition) // ERROR! Missing ;
// CORRECT
do {
printf("Hello\n");
} while (condition); // Semicolon required!

11Summary

🎯 Key Takeaways

  • TRUE/FALSE: 0 = false, any non-zero = true
  • for: Use when you know the count (init; condition; update)
  • while: Use when iterations are unknown (check first)
  • do-while: Use when loop must run at least once (check last)
  • break: Exit loop immediately
  • continue: Skip to next iteration
  • Infinite loops: while(1) with break for controlled exit

11Next Steps

Now that you understand loops, you're ready to organize code with functions!