Module 2.3

C Loops

Loops are the powerhouse of programming - they let you repeat actions without writing repetitive code. Master for, while, and do-while loops to automate tasks, process collections, and build efficient programs that can handle any amount of data.

40 min read
Beginner
Hands-on Examples
What You'll Learn
  • The for loop for counted iterations
  • The while loop for condition-based repetition
  • The do-while loop for guaranteed execution
  • Loop control with break and continue
  • Nested loops for multi-dimensional tasks
Contents
01

Introduction to Loops

Imagine having to print "Hello" 100 times. Without loops, you'd need 100 printf statements! Loops solve this by letting you write the code once and repeat it as many times as needed. They are essential for processing data, creating patterns, and automating repetitive tasks.

Beginner Tip: Think of loops like a playlist on repeat. The songs (code) play over and over until you hit stop (condition becomes false). Each play-through is called an "iteration."

What is a Loop?

A loop is a programming construct that repeats a block of code multiple times automatically. Instead of writing the same code over and over, you write it once inside a loop, and the computer executes it as many times as you need. The repetition continues until a specified condition becomes false, or until a break statement is encountered.

Real-world analogy: Think of brushing your teeth - you don't think "move brush left, move brush right" 100 separate times. You just repeat the motion until your teeth are clean. That's exactly what a loop does in programming!

Key Terms: Each execution of the loop body is called an iteration. A loop that runs 10 times has 10 iterations. The code inside the loop is called the loop body. The test that determines whether to continue is called the loop condition.

Why Do We Need Loops?

Loops are fundamental to programming because they eliminate repetition and enable automation. Here are real-world scenarios where loops are essential:

Data Processing

Process thousands of records in a database, calculate totals, find averages.

Searching

Find a specific item in a list, search for a pattern in text.

Game Development

Main game loop that updates graphics, checks input, and runs 60 times per second.

Input Validation

Keep asking for valid input until the user provides acceptable data.

Types of Loops in C

C provides three types of loops, each designed for different scenarios:

Loop Type Best For Condition Check Minimum Iterations
for Known number of iterations Before each iteration 0 (may not execute)
while Unknown iterations, condition-based Before each iteration 0 (may not execute)
do-while Need at least one execution After each iteration 1 (always executes once)

Anatomy of a Loop

Every loop has four essential components:

// The four parts of a loop:

// 1. INITIALIZATION - Set up the loop variable
int i = 0;

// 2. CONDITION - Checked before each iteration
while (i < 5) {
    
    // 3. BODY - Code that repeats
    printf("Iteration %d\n", i);
    
    // 4. UPDATE - Change the loop variable
    i++;
}

// Output:
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4
Warning: Forgetting the update step creates an infinite loop - a loop that never ends! Always ensure your condition will eventually become false.
02

The for Loop

The for loop is the most commonly used loop when you know exactly how many times you want to repeat. It combines initialization, condition, and update in a single compact line, making it perfect for counting, iterating through arrays, and controlled repetition.

Beginner Tip: Think of a for loop like climbing stairs. You start at the bottom (initialization), check if there are more stairs (condition), climb one step (body), then move up (update). Repeat until you reach the top!

The for Loop

The for loop is the most structured loop in C, designed for situations where you know exactly how many times you want to repeat something. It combines three essential parts into one compact line: where to start (initialization), when to stop (condition), and how to progress (update).

Real-world analogy: Imagine doing 10 push-ups. You start at count 1 (initialization), keep going while count is 10 or less (condition), and add 1 after each push-up (update). The for loop works exactly the same way!

Three parts explained:
1. Initialization (runs once at start): int i = 0 - sets up your counter
2. Condition (checked before each iteration): i < 10 - decides if loop continues
3. Update (runs after each iteration): i++ - changes the counter

Syntax: for (init; condition; update) { body } - Notice the semicolons separating each part, not commas!

Basic Syntax

// Syntax of for loop
for (initialization; condition; update) {
    // Code to repeat (loop body)
}

// How it works:
// 1. initialization - runs ONCE at the start
// 2. condition - checked BEFORE each iteration
// 3. body - executes if condition is true
// 4. update - runs AFTER each iteration
// 5. Go back to step 2

Simple Examples

Counting from 1 to 5
// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
    printf("%d ", i);
}
printf("\n");

// Output: 1 2 3 4 5
Step-by-Step Execution
Step i value Condition i <= 5 Action Output
1 1 true Print 1, then i++ 1
2 2 true Print 2, then i++ 1 2
3 3 true Print 3, then i++ 1 2 3
4 4 true Print 4, then i++ 1 2 3 4
5 5 true Print 5, then i++ 1 2 3 4 5
6 6 false Loop exits -
Final Output: 1 2 3 4 5
Counting Backwards
// Countdown from 5 to 1
for (int i = 5; i >= 1; i--) {
    printf("%d ", i);
}
printf("Blast off!\n");

// Output: 5 4 3 2 1 Blast off!
Decrementing: To count backwards, start high, use >= condition, and decrement with i--. The loop runs while i is greater than or equal to 1.
Custom Step Size
// Print even numbers from 2 to 10
for (int i = 2; i <= 10; i += 2) {
    printf("%d ", i);
}
printf("\n");

// Output: 2 4 6 8 10

// Print multiples of 5
for (int i = 5; i <= 25; i += 5) {
    printf("%d ", i);
}
printf("\n");

// Output: 5 10 15 20 25
Custom Increments: Use i += 2 to count by twos, i += 5 to count by fives. You can use any increment value, including variables.
Sum of Numbers
#include <stdio.h>

int main() {
    int sum = 0;
    
    // Calculate sum of 1 to 10
    for (int i = 1; i <= 10; i++) {
        sum += i;  // Same as: sum = sum + i
    }
    
    printf("Sum of 1 to 10 = %d\n", sum);
    
    return 0;
}

// Output: Sum of 1 to 10 = 55

Common for Loop Patterns

Printing a Pattern
// Print 5 stars
for (int i = 0; i < 5; i++) {
    printf("* ");
}
printf("\n");

// Output: * * * * *
Multiplication Table
int num = 7;

printf("Multiplication table for %d:\n", num);
for (int i = 1; i <= 10; i++) {
    printf("%d x %d = %d\n", num, i, num * i);
}

// Output:
// Multiplication table for 7:
// 7 x 1 = 7
// 7 x 2 = 14
// ...
// 7 x 10 = 70
Factorial Calculation
int n = 5;
int factorial = 1;

for (int i = 1; i <= n; i++) {
    factorial *= i;  // factorial = factorial * i
}

printf("%d! = %d\n", n, factorial);

// Output: 5! = 120
// (1 * 2 * 3 * 4 * 5 = 120)

Practice Questions: for Loop

Task: Use a for loop to print all odd numbers from 1 to 15.

Expected output: 1 3 5 7 9 11 13 15

Hint: Start at 1 and increment by 2, or use modulus operator.

Show Solution
#include <stdio.h>

int main() {
    // Method 1: Start at 1, step by 2
    for (int i = 1; i <= 15; i += 2) {
        printf("%d ", i);
    }
    printf("\n");
    
    // Method 2: Check if odd using modulus
    for (int i = 1; i <= 15; i++) {
        if (i % 2 != 0) {
            printf("%d ", i);
        }
    }
    
    return 0;
}

Given:

int n = 5;

Task: Calculate 1² + 2² + 3² + 4² + 5² = 55

Expected output: Sum of squares from 1 to 5 = 55

Show Solution
#include <stdio.h>

int main() {
    int n = 5;
    int sumSquares = 0;
    
    for (int i = 1; i <= n; i++) {
        sumSquares += i * i;
    }
    
    printf("Sum of squares from 1 to %d = %d\n", n, sumSquares);
    
    return 0;
}

// 1 + 4 + 9 + 16 + 25 = 55

Given:

int n = 10;

Task: Print the first 10 Fibonacci numbers (each number is sum of previous two).

Expected output: 0 1 1 2 3 5 8 13 21 34

Show Solution
#include <stdio.h>

int main() {
    int n = 10;
    int first = 0, second = 1, next;
    
    printf("First %d Fibonacci numbers:\n", n);
    
    for (int i = 0; i < n; i++) {
        if (i <= 1) {
            next = i;
        } else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d ", next);
    }
    printf("\n");
    
    return 0;
}

Given:

int num = 17;

Task: Use a for loop to check if the number is prime (divisible only by 1 and itself).

Expected output: 17 is a prime number

Hint: Check divisibility from 2 to num/2 or sqrt(num).

Show Solution
#include <stdio.h>

int main() {
    int num = 17;
    int isPrime = 1;  // Assume prime
    
    if (num <= 1) {
        isPrime = 0;
    } else {
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }
    
    if (isPrime) {
        printf("%d is a prime number\n", num);
    } else {
        printf("%d is not a prime number\n", num);
    }
    
    return 0;
}

Given:

int base = 2, exponent = 10;

Task: Calculate base raised to exponent using a for loop (2^10 = 1024).

Expected output: 2^10 = 1024

Show Solution
#include <stdio.h>

int main() {
    int base = 2, exponent = 10;
    long long result = 1;
    
    for (int i = 0; i < exponent; i++) {
        result *= base;
    }
    
    printf("%d^%d = %lld\n", base, exponent, result);
    
    return 0;
}

// 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 1024
03

The while Loop

The while loop is your go-to when you don't know in advance how many times you need to repeat. It keeps executing as long as a condition remains true - perfect for reading user input, processing files, or waiting for events.

Beginner Tip: Think of a while loop like "keep eating while you're hungry." You don't know exactly how many bites you'll take - you just keep going until you're full (condition becomes false).

The while Loop

The while loop is the simplest and most flexible loop in C. It repeats a block of code as long as a specified condition remains true. Unlike the for loop, you don't need to know in advance how many times it will run - it just keeps going until the condition becomes false.

Real-world analogy: Think of filling a bucket with water. You don't count how many cups you'll pour - you just keep pouring WHILE the bucket is not full. Once it's full (condition false), you stop. That's exactly how a while loop thinks!

Important behavior: The condition is checked BEFORE each iteration. This means if the condition is false from the very beginning, the loop body will never execute - not even once. This is called a "pre-test" or "entry-controlled" loop.

Syntax: while (condition) { body } - Remember to update something inside the loop that will eventually make the condition false, or you'll create an infinite loop!

Basic Syntax

// Syntax of while loop
while (condition) {
    // Code to repeat (loop body)
    // Must include something that eventually makes condition false!
}

// How it works:
// 1. Check condition
// 2. If true, execute body, then go to step 1
// 3. If false, exit loop

Simple Examples

Basic Counter
int count = 1;

while (count <= 5) {
    printf("Count: %d\n", count);
    count++;  // Don't forget this!
}

// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
Critical: Without count++, the condition count <= 5 would always be true (since count stays at 1), creating an infinite loop that never stops!
Sum Until Zero
#include <stdio.h>

int main() {
    int num;
    int sum = 0;
    
    printf("Enter numbers (0 to stop):\n");
    scanf("%d", &num);
    
    while (num != 0) {
        sum += num;
        scanf("%d", &num);
    }
    
    printf("Total sum: %d\n", sum);
    
    return 0;
}

// Sample run:
// Enter numbers (0 to stop):
// 5
// 10
// 3
// 0
// Total sum: 18
Sentinel Value: Using 0 as a "stop signal" is called a sentinel value. The loop keeps running until the user enters the special value (0) that signals "I'm done."
Digit Counter
int number = 12345;
int digits = 0;

while (number > 0) {
    digits++;
    number /= 10;  // Remove last digit
}

printf("Number of digits: %d\n", digits);

// Output: Number of digits: 5
// Process: 12345 -> 1234 -> 123 -> 12 -> 1 -> 0
Find First Digit
int number = 9876;

while (number >= 10) {
    number /= 10;
}

printf("First digit: %d\n", number);

// Output: First digit: 9
// Process: 9876 -> 987 -> 98 -> 9

while vs for: When to Use Which?

Use for When:
  • You know exact iteration count
  • Iterating through arrays
  • Counting up or down
  • Index is important
// Known iterations
for (int i = 0; i < 10; i++) {
    printf("%d ", i);
}
Use while When:
  • Unknown number of iterations
  • Waiting for a condition
  • Reading user input until done
  • Processing until end of data
// Unknown iterations
while (userInput != 0) {
    scanf("%d", &userInput);
}

Practice Questions: while Loop

Task: Use a while loop to print: 1, 2, 4, 8, 16, 32, 64, 128, 256

Hint: Start at 1, multiply by 2 each iteration.

Show Solution
#include <stdio.h>

int main() {
    int power = 1;
    
    while (power <= 256) {
        printf("%d ", power);
        power *= 2;  // Double the value
    }
    printf("\n");
    
    return 0;
}

Given:

int num = 12345;

Task: Reverse the digits to get 54321.

Expected output: Reversed: 54321

Show Solution
#include <stdio.h>

int main() {
    int num = 12345;
    int reversed = 0;
    
    while (num > 0) {
        int digit = num % 10;       // Get last digit
        reversed = reversed * 10 + digit;  // Add to reversed
        num /= 10;                  // Remove last digit
    }
    
    printf("Reversed: %d\n", reversed);
    
    return 0;
}

Given:

int a = 48, b = 18;

Task: Find GCD (Greatest Common Divisor) using while loop.

Expected output: GCD of 48 and 18 = 6

Hint: GCD(a, b) = GCD(b, a % b) until b becomes 0.

Show Solution
#include <stdio.h>

int main() {
    int a = 48, b = 18;
    int original_a = a, original_b = b;
    
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    
    printf("GCD of %d and %d = %d\n", original_a, original_b, a);
    
    return 0;
}

// Steps: (48,18) -> (18,12) -> (12,6) -> (6,0)
// GCD = 6

Given:

int num = 12321;

Task: Check if the number reads the same forwards and backwards.

Expected output: 12321 is a palindrome

Hint: Reverse the number and compare with original.

Show Solution
#include <stdio.h>

int main() {
    int num = 12321;
    int original = num;
    int reversed = 0;
    
    while (num > 0) {
        int digit = num % 10;
        reversed = reversed * 10 + digit;
        num /= 10;
    }
    
    if (original == reversed) {
        printf("%d is a palindrome\n", original);
    } else {
        printf("%d is not a palindrome\n", original);
    }
    
    return 0;
}

Given:

int decimal = 25;

Task: Convert decimal 25 to binary using while loop.

Expected output: 25 in binary = 11001

Hint: Repeatedly divide by 2 and collect remainders.

Show Solution
#include <stdio.h>

int main() {
    int decimal = 25;
    int original = decimal;
    int binary = 0;
    int place = 1;
    
    while (decimal > 0) {
        int remainder = decimal % 2;
        binary += remainder * place;
        place *= 10;
        decimal /= 2;
    }
    
    printf("%d in binary = %d\n", original, binary);
    
    return 0;
}

// 25 / 2 = 12 rem 1
// 12 / 2 = 6 rem 0
// 6 / 2 = 3 rem 0
// 3 / 2 = 1 rem 1
// 1 / 2 = 0 rem 1
// Binary: 11001
04

The do-while Loop

The do-while loop is the "execute first, ask questions later" loop. Unlike for and while, it guarantees the loop body runs at least once - perfect for menus, input validation, and situations where you need at least one execution.

Beginner Tip: Think of do-while like a restaurant where you must order at least one item. You order (execute), then decide if you want more (check condition). You can't leave without ordering once!

The do-while Loop

The do-while loop is unique because it follows a "do first, ask questions later" approach. It executes the loop body first, THEN checks the condition. This guarantees the code runs at least once, regardless of whether the condition is initially true or false.

Real-world analogy: Think of a restaurant where you MUST order at least one dish. You order (execute), then the waiter asks "Would you like anything else?" (check condition). Even if you say no, you've already ordered once. That's the do-while loop - execute first, then decide to continue!

When to use it: The do-while loop is perfect for:
- Menu systems (show menu at least once)
- Input validation (get input at least once before checking)
- Games (play at least one round)
- Any situation where "at least once" is required

Syntax: do { body } while (condition); - Don't forget the semicolon after the closing parenthesis! This is a common syntax error that confuses beginners.

Basic Syntax

// Syntax of do-while loop
do {
    // Code to repeat (loop body)
    // Executes AT LEAST ONCE
} while (condition);  // Don't forget the semicolon!

// How it works:
// 1. Execute body FIRST
// 2. Check condition
// 3. If true, go to step 1
// 4. If false, exit loop
Common Mistake: Don't forget the semicolon after while (condition); - it's required and forgetting it causes syntax errors!

Key Difference: while vs do-while

int x = 10;

// while - checks FIRST, may not execute
while (x < 5) {
    printf("while: %d\n", x);
    x++;
}
// Output: (nothing - condition false from start)

// do-while - executes FIRST, then checks
do {
    printf("do-while: %d\n", x);
    x++;
} while (x < 5);
// Output: do-while: 10
// (executes once even though 10 < 5 is false)
The difference: When x starts at 10 and condition is x < 5 (false), the while loop never runs, but the do-while runs once because it checks AFTER executing.

Practical Examples

Menu-Driven Program
#include <stdio.h>

int main() {
    int choice;
    
    do {
        printf("\n=== Calculator Menu ===\n");
        printf("1. Add\n");
        printf("2. Subtract\n");
        printf("3. Multiply\n");
        printf("4. Exit\n");
        printf("Enter choice: ");
        scanf("%d", &choice);
        
        switch (choice) {
            case 1: printf("You chose Add\n"); break;
            case 2: printf("You chose Subtract\n"); break;
            case 3: printf("You chose Multiply\n"); break;
            case 4: printf("Goodbye!\n"); break;
            default: printf("Invalid choice!\n");
        }
    } while (choice != 4);
    
    return 0;
}
Why do-while here? A menu should always display at least once. The user needs to see the options before making a choice. After choosing, we check if they want to continue (choice != 4).
Input Validation
#include <stdio.h>

int main() {
    int age;
    
    do {
        printf("Enter your age (1-120): ");
        scanf("%d", &age);
        
        if (age < 1 || age > 120) {
            printf("Invalid age! Try again.\n");
        }
    } while (age < 1 || age > 120);
    
    printf("Your age is %d\n", age);
    
    return 0;
}

// Sample run:
// Enter your age (1-120): -5
// Invalid age! Try again.
// Enter your age (1-120): 150
// Invalid age! Try again.
// Enter your age (1-120): 25
// Your age is 25
Guessing Game
#include <stdio.h>

int main() {
    int secret = 7;  // The number to guess
    int guess;
    int attempts = 0;
    
    do {
        printf("Guess the number (1-10): ");
        scanf("%d", &guess);
        attempts++;
        
        if (guess < secret) {
            printf("Too low!\n");
        } else if (guess > secret) {
            printf("Too high!\n");
        }
    } while (guess != secret);
    
    printf("Correct! You got it in %d attempts.\n", attempts);
    
    return 0;
}

Practice Questions: do-while Loop

Task: Keep asking user for a number until they enter a positive number (> 0).

Hint: Use do-while since you need at least one input.

Show Solution
#include <stdio.h>

int main() {
    int num;
    
    do {
        printf("Enter a positive number: ");
        scanf("%d", &num);
        
        if (num <= 0) {
            printf("That's not positive! Try again.\n");
        }
    } while (num <= 0);
    
    printf("You entered: %d\n", num);
    
    return 0;
}

Given:

int num = 12345;

Task: Calculate sum of digits (1+2+3+4+5 = 15) using do-while.

Expected output: Sum of digits: 15

Show Solution
#include <stdio.h>

int main() {
    int num = 12345;
    int sum = 0;
    
    do {
        sum += num % 10;  // Add last digit
        num /= 10;        // Remove last digit
    } while (num > 0);
    
    printf("Sum of digits: %d\n", sum);
    
    return 0;
}

Task: Allow user 3 attempts to enter correct password (1234). Lock after 3 failed attempts.

Show Solution
#include <stdio.h>

int main() {
    int password = 1234;
    int attempt;
    int tries = 0;
    int maxTries = 3;
    
    do {
        printf("Enter password: ");
        scanf("%d", &attempt);
        tries++;
        
        if (attempt == password) {
            printf("Access granted!\n");
            break;
        } else {
            printf("Wrong! %d attempts remaining.\n", maxTries - tries);
        }
    } while (tries < maxTries);
    
    if (attempt != password) {
        printf("Account locked!\n");
    }
    
    return 0;
}

Task: Keep reading numbers and calculate average. Stop when user enters a negative number.

Hint: Track sum and count, exclude the negative number from calculation.

Show Solution
#include <stdio.h>

int main() {
    int num;
    int sum = 0;
    int count = 0;
    
    do {
        printf("Enter a number (negative to stop): ");
        scanf("%d", &num);
        
        if (num >= 0) {
            sum += num;
            count++;
        }
    } while (num >= 0);
    
    if (count > 0) {
        printf("Average: %.2f\n", (float)sum / count);
    } else {
        printf("No numbers entered.\n");
    }
    
    return 0;
}

Given:

int balance = 1000;

Task: Create an ATM that allows withdrawals. Validate amount (must be positive, multiple of 10, and not exceed balance). Keep asking until valid.

Show Solution
#include <stdio.h>

int main() {
    int balance = 1000;
    int amount;
    int valid;
    
    printf("Current balance: $%d\n", balance);
    
    do {
        printf("Enter withdrawal amount: $");
        scanf("%d", &amount);
        
        valid = 1;
        
        if (amount <= 0) {
            printf("Amount must be positive!\n");
            valid = 0;
        } else if (amount % 10 != 0) {
            printf("Amount must be multiple of 10!\n");
            valid = 0;
        } else if (amount > balance) {
            printf("Insufficient funds!\n");
            valid = 0;
        }
    } while (!valid);
    
    balance -= amount;
    printf("Dispensing $%d\n", amount);
    printf("New balance: $%d\n", balance);
    
    return 0;
}
05

Loop Control Statements

Sometimes you need more control over your loops - exit early when you find what you're looking for, or skip certain iterations. C provides break and continue statements to give you this fine-grained control.

Beginner Tip: Think of break as an emergency exit - you leave the building immediately. Continue is like skipping a song on a playlist - you move to the next one without stopping the music.

The break Statement

break

The break statement is like an emergency exit door - when you hit it, you immediately leave the loop, no questions asked. Execution jumps straight to the first line of code after the loop ends. The remaining iterations are completely skipped.

Real-world analogy: Imagine searching for your keys in 10 drawers. If you find them in drawer 3, you stop searching immediately - you don't check drawers 4 through 10. That's exactly what break does: "Found it! Stop the loop!"

Common uses:
- Search algorithms (stop when item is found)
- Input processing (stop on special "quit" value)
- Error handling (exit loop when error occurs)
- Early termination when goal is achieved

Important: In nested loops, break only exits the INNERMOST loop. To exit multiple loops, you need additional logic like flags or goto.

Finding a Value
int numbers[] = {10, 25, 33, 47, 52, 61};
int target = 33;
int found = 0;

for (int i = 0; i < 6; i++) {
    if (numbers[i] == target) {
        printf("Found %d at index %d\n", target, i);
        found = 1;
        break;  // Exit immediately - no need to check more
    }
}

if (!found) {
    printf("%d not found\n", target);
}

// Output: Found 33 at index 2
Exit on Special Input
int sum = 0;
int num;

printf("Enter numbers (-1 to stop):\n");

while (1) {  // Infinite loop
    scanf("%d", &num);
    
    if (num == -1) {
        break;  // Exit the infinite loop
    }
    
    sum += num;
}

printf("Sum: %d\n", sum);

The continue Statement

continue

The continue statement is like a "skip this one" button. When encountered, it immediately stops the current iteration and jumps to the next one. Unlike break, the loop keeps running - you're just skipping ONE particular iteration, not exiting entirely.

Real-world analogy: Imagine you're a teacher grading papers, but you skip any paper that's blank. You don't stop grading entirely (that would be break) - you just skip the blank one and move to the next paper. That's continue!

Common uses:
- Skip invalid or unwanted data
- Filter out certain values (like negatives or zeros)
- Skip special cases that don't need processing
- Avoid deeply nested if-else structures

Behavior in different loops: In for loops, continue jumps to the update statement (i++). In while/do-while loops, it jumps directly to the condition check. Make sure your loop variable still gets updated!

Skip Certain Values
// Print only odd numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    printf("%d ", i);
}
printf("\n");

// Output: 1 3 5 7 9
Skip Invalid Data
int scores[] = {85, -1, 92, 78, -1, 95, 88};
int sum = 0;
int count = 0;

for (int i = 0; i < 7; i++) {
    if (scores[i] < 0) {
        continue;  // Skip invalid scores
    }
    sum += scores[i];
    count++;
}

printf("Average (valid scores): %.1f\n", (float)sum / count);

// Output: Average (valid scores): 87.6

break vs continue Comparison

// Demonstrating the difference
printf("Using break:\n");
for (int i = 1; i <= 5; i++) {
    if (i == 3) break;
    printf("%d ", i);
}
printf("\n");  // Output: 1 2

printf("Using continue:\n");
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    printf("%d ", i);
}
printf("\n");  // Output: 1 2 4 5
break
  • Exits the loop completely
  • No more iterations
  • Use when done with loop
continue
  • Skips current iteration only
  • Loop continues with next iteration
  • Use to skip certain values

Practice Questions: Loop Control

Given:

int arr[] = {5, 12, -3, 8, -7, 15};

Task: Find and print the first negative number, then stop searching.

Expected output: First negative: -3

Show Solution
#include <stdio.h>

int main() {
    int arr[] = {5, 12, -3, 8, -7, 15};
    int size = 6;
    
    for (int i = 0; i < size; i++) {
        if (arr[i] < 0) {
            printf("First negative: %d\n", arr[i]);
            break;
        }
    }
    
    return 0;
}

Given:

int arr[] = {10, -5, 20, -8, 30, -2};

Task: Calculate sum of only positive numbers using continue.

Expected output: Sum of positives: 60

Show Solution
#include <stdio.h>

int main() {
    int arr[] = {10, -5, 20, -8, 30, -2};
    int size = 6;
    int sum = 0;
    
    for (int i = 0; i < size; i++) {
        if (arr[i] < 0) {
            continue;  // Skip negative numbers
        }
        sum += arr[i];
    }
    
    printf("Sum of positives: %d\n", sum);
    
    return 0;
}

// 10 + 20 + 30 = 60

Task: Print numbers from 1 to 20, but skip all multiples of 3.

Expected output: 1 2 4 5 7 8 10 11 13 14 16 17 19 20

Show Solution
#include <stdio.h>

int main() {
    for (int i = 1; i <= 20; i++) {
        if (i % 3 == 0) {
            continue;  // Skip multiples of 3
        }
        printf("%d ", i);
    }
    printf("\n");
    
    return 0;
}

Given:

int arr[] = {4, 6, 8, 11, 15, 17};

Task: Find and print the first prime number, then stop.

Expected output: First prime: 11

Show Solution
#include <stdio.h>

int main() {
    int arr[] = {4, 6, 8, 11, 15, 17};
    int size = 6;
    
    for (int i = 0; i < size; i++) {
        int num = arr[i];
        int isPrime = 1;
        
        if (num <= 1) {
            isPrime = 0;
        } else {
            for (int j = 2; j <= num / 2; j++) {
                if (num % j == 0) {
                    isPrime = 0;
                    break;
                }
            }
        }
        
        if (isPrime) {
            printf("First prime: %d\n", num);
            break;  // Stop after finding first prime
        }
    }
    
    return 0;
}

Given:

int arr[] = {15, 25, 30, 40, 50, 60};

Task: Add numbers until sum exceeds 100. Print how many numbers were added and the final sum.

Expected output: Added 4 numbers, Sum = 110

Show Solution
#include <stdio.h>

int main() {
    int arr[] = {15, 25, 30, 40, 50, 60};
    int size = 6;
    int sum = 0;
    int count = 0;
    
    for (int i = 0; i < size; i++) {
        sum += arr[i];
        count++;
        
        if (sum > 100) {
            break;  // Stop when sum exceeds 100
        }
    }
    
    printf("Added %d numbers, Sum = %d\n", count, sum);
    
    return 0;
}

// 15 + 25 + 30 + 40 = 110 > 100
06

Nested Loops

A nested loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop. This is essential for working with 2D data like tables, matrices, and creating patterns.

Beginner Tip: Think of nested loops like a clock - the minute hand (inner loop) completes 60 rotations for every single rotation of the hour hand (outer loop).

Basic Nested Loop

// Nested loop structure
for (int i = 1; i <= 3; i++) {         // Outer loop: 3 iterations
    printf("Outer i=%d: ", i);
    
    for (int j = 1; j <= 4; j++) {     // Inner loop: 4 iterations each time
        printf("j=%d ", j);
    }
    printf("\n");
}

// Output:
// Outer i=1: j=1 j=2 j=3 j=4
// Outer i=2: j=1 j=2 j=3 j=4
// Outer i=3: j=1 j=2 j=3 j=4

// Total inner loop executions: 3 x 4 = 12

Pattern Printing

Rectangle of Stars
int rows = 3, cols = 5;

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        printf("* ");
    }
    printf("\n");
}

// Output:
// * * * * *
// * * * * *
// * * * * *
Right Triangle
int n = 5;

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        printf("* ");
    }
    printf("\n");
}

// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
Number Triangle
int n = 4;

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        printf("%d ", j);
    }
    printf("\n");
}

// Output:
// 1
// 1 2
// 1 2 3
// 1 2 3 4

Multiplication Table

#include <stdio.h>

int main() {
    printf("Multiplication Table (1-5):\n\n");
    
    // Header row
    printf("    ");
    for (int i = 1; i <= 5; i++) {
        printf("%4d", i);
    }
    printf("\n    --------------------\n");
    
    // Table body
    for (int i = 1; i <= 5; i++) {
        printf("%2d |", i);
        for (int j = 1; j <= 5; j++) {
            printf("%4d", i * j);
        }
        printf("\n");
    }
    
    return 0;
}

// Output:
//        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

Practice Questions: Nested Loops

Task: Print an inverted right triangle with 5 rows.

Expected output:

* * * * *
* * * *
* * *
* *
*
Show Solution
#include <stdio.h>

int main() {
    int n = 5;
    
    for (int i = n; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    
    return 0;
}

Task: Print a 5x5 hollow square (stars only on borders).

Expected output:

* * * * *
*       *
*       *
*       *
* * * * *
Show Solution
#include <stdio.h>

int main() {
    int n = 5;
    
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            // Print * if on border (first/last row or first/last column)
            if (i == 1 || i == n || j == 1 || j == n) {
                printf("* ");
            } else {
                printf("  ");
            }
        }
        printf("\n");
    }
    
    return 0;
}

Task: Print a centered pyramid with 5 rows.

Expected output:

    *
   * *
  * * *
 * * * *
* * * * *
Show Solution
#include <stdio.h>

int main() {
    int n = 5;
    
    for (int i = 1; i <= n; i++) {
        // Print spaces
        for (int j = 1; j <= n - i; j++) {
            printf(" ");
        }
        // Print stars
        for (int k = 1; k <= i; k++) {
            printf("* ");
        }
        printf("\n");
    }
    
    return 0;
}

Task: Print Floyd's Triangle with 4 rows (consecutive numbers in triangle).

Expected output:

1
2 3
4 5 6
7 8 9 10
Show Solution
#include <stdio.h>

int main() {
    int n = 4;
    int num = 1;
    
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%d ", num);
            num++;
        }
        printf("\n");
    }
    
    return 0;
}

Task: Print a diamond shape with 5 rows on top and 4 rows on bottom.

Expected output:

    *
   * *
  * * *
 * * * *
* * * * *
 * * * *
  * * *
   * *
    *
Show Solution
#include <stdio.h>

int main() {
    int n = 5;
    
    // Upper half (pyramid)
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            printf(" ");
        }
        for (int k = 1; k <= i; k++) {
            printf("* ");
        }
        printf("\n");
    }
    
    // Lower half (inverted pyramid)
    for (int i = n - 1; i >= 1; i--) {
        for (int j = 1; j <= n - i; j++) {
            printf(" ");
        }
        for (int k = 1; k <= i; k++) {
            printf("* ");
        }
        printf("\n");
    }
    
    return 0;
}

Key Takeaways

for - Known Iterations

Use for when you know exactly how many times to repeat. Combines init, condition, and update in one line.

while - Condition-Based

Use while when iterations depend on a condition. May not execute if condition is initially false.

do-while - At Least Once

Use do-while when you need at least one execution. Perfect for menus and input validation.

break - Exit Immediately

Use break to exit a loop early. Commonly used when you find what you're looking for.

continue - Skip Iteration

Use continue to skip the current iteration. Loop continues with the next cycle.

Avoid Infinite Loops

Always ensure your loop condition will eventually become false. Update loop variables correctly.

Knowledge Check

Quick Quiz

Test what you've learned about C loops

1 How many times will this loop execute?
for (int i = 0; i < 5; i++) { }
2 Which loop guarantees at least one execution?
3 What does the break statement do in a loop?
4 What is the output?
for (int i = 1; i <= 3; i++) { if (i == 2) continue; printf("%d ", i); }
5 In a nested loop with outer loop running 3 times and inner loop running 4 times, how many total iterations of the inner loop?
6 What's missing in this infinite loop?
int i = 0; while (i < 5) { printf("%d", i); }
Answer all questions to check your score