2.5) Loops

Loops in C are essential for repeating a set of instructions multiple times. They help automate repetitive tasks and perform iterations over a range of values.

There are three main types of loops in C:

  • while,
  • for, and
  • do-while.

Let’s delve into each type with detailed explanations and code examples.

1. while Loop


The while loop repeatedly executes a block of code as long as a given condition remains true.

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

Example:

#include <stdio.h>

int main() {
    int count = 1;

    while (count <= 5) {
        printf("Count: %d\n", count);
        count++;  // Increment count for the next iteration
    }

    return 0;
}

Explanation:

  • The loop starts with the count variable initialized to 1.
  • The loop continues executing as long as the count is less than or equal to 5.
  • Inside the loop, the value of count is printed, and then it’s incremented by 1 using count++.
  • This loop will print the numbers from 1 to 5.

2. for Loop


The for loop is used for executing a block of code a specific number of times, controlled by an initialization, condition, and an increment/decrement.

for (initialization; condition; increment/decrement) {
    // Code to be executed repeatedly as long as the condition is true
}

Example:

#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        printf("Square of %d is %d\n", i, i * i);
    }

    return 0;
}

Explanation:

  • The loop starts with the initialization of the i variable to 1.
  • The loop continues executing as long as the value of i is less than or equal to 5.
  • After each iteration, the value of i is incremented by 1 (i++).
  • This loop calculates and prints the squares of the numbers from 1 to 5.

3. do-while Loop


The do-while loop executes a block of code at least once and then repeatedly as long as a given condition remains true.

do {
    // Code to be executed at least once and then repeatedly while the condition is true
} while (condition);

Example:

#include <stdio.h>

int main() {
    int num;

    do {
        printf("Enter a positive number: ");
        scanf("%d", &num);
    } while (num <= 0);

    printf("You entered a positive number: %d\n", num);

    return 0;
}

Explanation:

  • The loop starts by executing the block of code within the do section.
  • After the code execution, the condition (num <= 0) is checked.
  • If the condition is true, the loop continues, and the user is prompted to enter a positive number again.
  • The loop repeats until the user enters a positive number.