Control Flow: Loops (for, while, do-while)

Implementing repetitive tasks using `for`, `while`, and `do-while` loops.


C Programming: Loops Explained

Introduction to Loops

Loops are fundamental control flow structures in C that allow you to execute a block of code repeatedly. This repetition continues as long as a specified condition remains true. Loops are essential for automating repetitive tasks, processing data efficiently, and building complex algorithms.

Types of Loops in C

C provides three primary types of loops:

  • for loop
  • while loop
  • do-while loop

The for Loop

Syntax:

 for (initialization; condition; increment/decrement) {
    // Code to be executed repeatedly
} 

Explanation:

  • Initialization: Executed only once at the beginning of the loop. It usually initializes a loop counter variable.
  • Condition: Evaluated before each iteration. If the condition is true, the loop body is executed. If it's false, the loop terminates.
  • Increment/Decrement: Executed after each iteration. It typically updates the loop counter variable.

Examples:

Printing Numbers 1 to 10:

 #include <stdio.h>

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

Iterating through an Array:

 #include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate array size

    for (int i = 0; i < size; i++) {
        printf("Element at index %d: %d\n", i, numbers[i]);
    }

    return 0;
} 

The while Loop

Syntax:

 while (condition) {
    // Code to be executed repeatedly
} 

Explanation:

The while loop repeatedly executes a block of code as long as the specified condition remains true. The condition is checked before each iteration. If the condition is initially false, the loop body will not be executed at all.

Examples:

Counting Down from 10:

 #include <stdio.h>

int main() {
    int i = 10;
    while (i >= 1) {
        printf("%d ", i);
        i--;
    }
    printf("\n");
    return 0;
} 

Reading Input Until a Specific Value:

 #include <stdio.h>

int main() {
    int number;
    printf("Enter numbers (enter -1 to stop):\n");

    scanf("%d", &number); // Read the first number *before* the loop

    while (number != -1) {
        printf("You entered: %d\n", number);
        scanf("%d", &number); // Read the next number inside the loop
    }

    printf("Loop terminated.\n");
    return 0;
} 

The do-while Loop

Syntax:

 do {
    // Code to be executed repeatedly
} while (condition); 

Explanation:

The do-while loop is similar to the while loop, but with one crucial difference: the loop body is executed at least once, regardless of the initial condition. The condition is checked after each iteration.

Examples:

Printing Numbers at Least Once:

 #include <stdio.h>

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

    return 0;
} 

Input Validation:

 #include <stdio.h>

int main() {
    int age;

    do {
        printf("Enter your age (0-120): ");
        scanf("%d", &age);

        if (age < 0 || age > 120) {
            printf("Invalid age. Please enter a valid age.\n");
        }
    } while (age < 0 || age > 120);

    printf("You entered a valid age: %d\n", age);
    return 0;
} 

Loop Applications and Practical Examples

1. Calculating the Sum of Numbers:

 #include <stdio.h>

int main() {
    int n, i, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++) {
        sum += i;  // sum = sum + i;
    }

    printf("Sum = %d\n", sum);
    return 0;
} 

2. Calculating the Average of Numbers in an Array:

 #include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int sum = 0;
    float average;

    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }

    average = (float)sum / size;

    printf("Average = %.2f\n", average); // Use %.2f to format the float output
    return 0;
} 

3. Searching for an Element in an Array:

 #include <stdio.h>

int main() {
    int numbers[] = {5, 10, 15, 20, 25};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int search_value = 15;
    int found = 0; // Flag to indicate if the element is found
    int index = -1; // Store the index if found

    for (int i = 0; i < size; i++) {
        if (numbers[i] == search_value) {
            found = 1;
            index = i;
            break; // Exit the loop once the element is found
        }
    }

    if (found) {
        printf("%d found at index %d\n", search_value, index);
    } else {
        printf("%d not found in the array\n", search_value);
    }

    return 0;
} 

4. Generating Patterns:

Example: Printing a Right-Angled Triangle

 #include <stdio.h>

int main() {
    int rows;
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

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

    return 0;
} 

Example: Printing a Hollow Square

 #include <stdio.h>

int main() {
    int size;
    printf("Enter the size of the square: ");
    scanf("%d", &size);

    for (int i = 1; i <= size; i++) {
        for (int j = 1; j <= size; j++) {
            if (i == 1 || i == size || j == 1 || j == size) {
                printf("* ");
            } else {
                printf("  "); // Two spaces for a more symmetrical look
            }
        }
        printf("\n");
    }

    return 0;
} 

Loop Control Statements: break and continue

These statements allow you to alter the normal flow of execution within a loop.

break Statement:

The break statement terminates the loop immediately and transfers control to the statement following the loop.

 #include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break; // Exit the loop when i is 5
        }
        printf("%d ", i);
    }
    printf("\nLoop terminated.\n");
    return 0;
} 

continue Statement:

The continue statement skips the rest of the current iteration and proceeds to the next iteration of the loop.

 #include <stdio.h>

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