Loops in C

Loops in C allow programmers to execute a block of code multiple times based on a condition. Loops are essential for automation, iterating through data, and handling repetitive tasks efficiently. In this tutorial, we will explore the different types of loops in C and how to use them effectively.

Step 1: Understanding the Types of Loops

C provides three main types of loops:

  • For Loop: Used when the number of iterations is known.
  • While Loop: Executes as long as a condition is true.
  • Do-While Loop: Executes at least once before checking the condition.

Step 2: Using the For Loop

The for loop has a fixed number of iterations:

#include <stdio.h>

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

Step 3: Using the While Loop

The while loop runs as long as the condition is true:

#include <stdio.h>

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

Step 4: Using the Do-While Loop

The do-while loop executes at least once before checking the condition:

#include <stdio.h>

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

        return 0;
    }

Step 5: Using Break and Continue

Break: Exits the loop immediately.

for (int i = 0; i < 5; i++) {
        if (i == 3) {
            break;
        }
        printf("Iteration %d\n", i);
    }

Continue: Skips the current iteration and continues with the next.

for (int i = 0; i < 5; i++) {
        if (i == 3) {
            continue;
        }
        printf("Iteration %d\n", i);
    }

Step 6: Using Nested Loops

Loops can be nested inside each other:

#include <stdio.h>

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

Step 7: Best Practices for Using Loops

  • Use a for loop when the number of iterations is known.
  • Use a while loop when the number of iterations depends on user input or conditions.
  • Break out of loops when needed to improve efficiency.

Next Steps

Practice using loops by:

  • Creating a program to calculate the sum of numbers from 1 to 100.
  • Using loops to print patterns.
  • Implementing user input-based loops.

For further learning, visit the C Programming Tutorial.