C Loops

Repeating code execution with control structures

🔄 What are C Loops?

Loops in C allow you to execute a block of code repeatedly until a specific condition is met. They help automate repetitive tasks and make programs more efficient and concise.


// Simple loop example
for(int i = 1; i <= 3; i++) {
    printf("Hello %d\n", i);
}
                                    

Types of C Loops

🔢

For Loop

Best for counting and known iterations

for(int i = 0; i < 5; i++) {
    printf("%d ", i);
}

While Loop

Continues while condition is true

int i = 0;
while(i < 5) {
    printf("%d ", i);
    i++;
}

Do-While Loop

Executes at least once, then checks condition

int i = 0;
do {
    printf("%d ", i);
    i++;
} while(i < 5);
🔄

Nested Loops

Loops inside other loops

for(int i = 1; i <= 3; i++) {
    for(int j = 1; j <= 2; j++) {
        printf("%d-%d ", i, j);
    }
}

🔹 For Loop in Detail

The for loop excels when iteration count is predetermined, offering compact syntax that combines initialization, condition checking, and increment operations. Each component serves a specific purpose: initialization runs once before the loop starts, the condition is checked before each iteration, and the update executes after each iteration. For example, for(int i=0; i<10; i++) { sum += i; } adds numbers 0-9. You can declare loop variables in the initialization section (C99+), use complex update expressions like i+=2, or even leave components empty. Multiple variables can be managed using comma operators: for(i=0, j=10; i<j; i++, j--). For loops are ideal for array processing, implementing algorithms with known iteration counts, and generating sequences where the relationship between iterations is clear.

#include <stdio.h>

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

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Sum = 55

🔹 While Loop Examples

While loops in C programming are ideal when you don't know the exact number of iterations beforehand. The while keyword checks a condition before each iteration, and the loop continues executing as long as the condition remains true. For example, while (count < 10) { printf("%d", count); count++; } repeatedly prints numbers until the condition becomes false. This makes while loops perfect for scenarios like reading user input until a specific value is entered, processing data streams, or implementing game loops where the number of iterations depends on runtime conditions rather than predetermined counts.

🔸 Basic While Loop

#include <stdio.h>

int main() {
    int count = 1;
    
    while(count <= 3) {
        printf("Count is: %d\n", count);
        count++;  // Don't forget to increment!
    }
    
    // Finding factorial
    int num = 5, factorial = 1, i = 1;
    while(i <= num) {
        factorial *= i;
        i++;
    }
    printf("Factorial of %d = %d\n", num, factorial);
    
    return 0;
}

Output:

Count is: 1
Count is: 2
Count is: 3
Factorial of 5 = 120

🔹 Do-While Loop

The do-while loop guarantees that the code block executes at least once before checking the condition. Unlike regular while loops, do { statements; } while (condition); places the condition check at the end of the loop body. This structure ensures the code runs first, then evaluates whether to continue. For instance, do { printf("Enter number: "); scanf("%d", &num); } while (num != 0); always prompts the user at least once. This makes do-while loops particularly useful for menu systems, input validation scenarios, and situations where initial execution is mandatory regardless of the condition state.

#include <stdio.h>

int main() {
    int choice;
    
    do {
        printf("Menu:\n");
        printf("1. Say Hello\n");
        printf("2. Exit\n");
        printf("Enter choice: ");
        scanf("%d", &choice);
        
        if(choice == 1) {
            printf("Hello there!\n");
        }
    } while(choice != 2);
    
    printf("Goodbye!\n");
    return 0;
}

Sample Output:

Menu:
1. Say Hello
2. Exit
Enter choice: 1
Hello there!
Menu:
1. Say Hello
2. Exit
Enter choice: 2
Goodbye!

🔹 Loop Control Statements

Loop control statements like break and continue provide fine-grained control over loop execution flow. The break statement immediately terminates the loop and transfers control to the next statement after the loop, while continue skips the remaining code in the current iteration and jumps to the next iteration. For example, if (i == 5) break; exits the loop entirely when i equals 5, whereas if (i % 2 == 0) continue; skips even numbers but keeps the loop running. These statements help optimize loop performance and implement complex conditional logic efficiently.

Break and Continue:

  • break: Exits the loop immediately
  • continue: Skips current iteration, goes to next
#include <stdio.h>

int main() {
    // Using break
    for(int i = 1; i <= 10; i++) {
        if(i == 6) {
            break;  // Exit loop when i is 6
        }
        printf("%d ", i);
    }
    printf("\nLoop ended with break\n");
    
    // Using continue
    printf("Even numbers: ");
    for(int i = 1; i <= 10; i++) {
        if(i % 2 != 0) {
            continue;  // Skip odd numbers
        }
        printf("%d ", i);
    }
    printf("\n");
    
    return 0;
}

Output:

1 2 3 4 5 
Loop ended with break
Even numbers: 2 4 6 8 10

🔹 Nested Loops Pattern

Nested loops allow you to create complex patterns by placing one loop inside another loop structure. The outer loop controls rows while the inner loop controls columns, enabling the creation of two-dimensional patterns and matrix operations. For example, for (int i = 0; i < 5; i++) { for (int j = 0; j <= i; j++) { printf("*"); } printf("\n"); } generates a triangle pattern. Nested loops are essential for working with multi-dimensional arrays, generating geometric patterns, implementing sorting algorithms like bubble sort, and processing grid-based data structures in game development and scientific computing applications.

#include <stdio.h>

int main() {
    // Star pattern
    for(int i = 1; i <= 4; i++) {
        for(int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    
    // Multiplication table
    printf("\nMultiplication Table (3x3):\n");
    for(int i = 1; i <= 3; i++) {
        for(int j = 1; j <= 3; j++) {
            printf("%d ", i * j);
        }
        printf("\n");
    }
    
    return 0;
}

Output:

* 
* * 
* * * 
* * * * 

Multiplication Table (3x3):
1 2 3 
2 4 6 
3 6 9

🧠 Test Your Knowledge

Which loop executes at least once even if condition is false?