Explain different types of loops in C with examples.

C provides three primary types of loops to perform repetitive tasks: for, while, and do-while loops.

  • For Loop: The for loop is used when the number of iterations is known beforehand. It has three parts: initialization, condition check, and increment/decrement. Example:

    for (int i = 0; i < 5; i++) {
    printf(“%d “, i);
    }
    // Output: 0 1 2 3 4
  • While Loop: The while loop repeats as long as the specified condition is true. The condition is checked before the execution of the loop’s body. Example:

    int i = 0;
    while (i < 5) {
    printf(“%d “, i);
    i++;
    }
    // Output: 0 1 2 3 4
  • Do-While Loop: The do-while loop guarantees that the body of the loop is executed at least once. The condition is checked after executing the loop body. Example:

    int i = 0;
    do {
    printf(“%d “, i);
    i++;
    } while (i < 5);
    // Output: 0 1 2 3 4

Each loop type is useful in different scenarios depending on whether the number of iterations is known in advance or whether the loop should always execute at least once.