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

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


The 'for' Loop in C Programming

Explanation: The `for` Loop

The for loop is a fundamental control flow statement in C that allows you to repeatedly execute a block of code a specific number of times. It's particularly useful when you know in advance how many iterations are needed. It provides a concise way to initialize a counter, check a condition, and update the counter within a single statement.

Detailed Explanation of the `for` Loop Syntax

The general syntax of the for loop in C is as follows:

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

Components of the `for` Loop:

1. Initialization

The initialization statement is executed only once, at the very beginning of the loop. It's typically used to initialize a counter variable. This variable will control how many times the loop iterates.

Example: int i = 0; This declares an integer variable i and initializes it to 0.

2. Condition

The condition is an expression that is evaluated before each iteration of the loop. If the condition is true (non-zero), the code inside the loop's curly braces is executed. If the condition is false (zero), the loop terminates, and control passes to the next statement after the loop.

Example: i < 10; This checks if the value of i is less than 10. The loop will continue as long as i is less than 10.

3. Increment/Decrement

The increment/decrement statement is executed after each iteration of the loop, after the code inside the curly braces has been executed. It's typically used to update the counter variable, usually by incrementing or decrementing it.

Example: i++; This increments the value of i by 1 (equivalent to i = i + 1;). i--; would decrement the value of i by 1. You can also use other update operations like i += 2; (increment by 2) or i *= 2; (multiply by 2).

Examples and Use Cases of `for` Loops

Example 1: Printing Numbers from 1 to 10

 #include <stdio.h>

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

Explanation: This loop initializes i to 1. It continues as long as i is less than or equal to 10. After each iteration, i is incremented by 1. The printf statement prints the current value of i in each iteration.

Example 2: Calculating the Sum of Numbers from 1 to n

 #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;  // Equivalent to sum = sum + i;
    }

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

    return 0;
} 

Explanation: This program takes a positive integer n as input. The for loop iterates from 1 to n, adding each number to the sum variable. Finally, it prints the calculated sum.

Example 3: Iterating Through an Array

 #include <stdio.h>

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

    printf("Elements of the array:\n");
    for (i = 0; i < size; i++) {
        printf("numbers[%d] = %d\n", i, numbers[i]);
    }

    return 0;
} 

Explanation: This example shows how to use a for loop to iterate through the elements of an array. The sizeof operator is used to determine the size of the array. The loop iterates from index 0 to size - 1, accessing each element of the array using the index i.

Example 4: Nested `for` Loops (Creating a Pattern)

 #include <stdio.h>

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

Explanation: This example uses nested for loops to print a pattern of asterisks. The outer loop controls the number of rows, and the inner loop controls the number of asterisks printed in each row.

Use Cases:

  • Repeating a task a fixed number of times.
  • Iterating over elements of an array or string.
  • Generating sequences of numbers or characters.
  • Performing calculations that require multiple iterations.
  • Implementing algorithms that involve repetition.
  • Creating patterns or visual representations.