Loops in C Programming

What is a Loop?

A loop is a programming construct that allows you to repeat a block of code multiple times.

Instead of writing the same code repeatedly, loops help automate repetitive tasks efficiently.

Why Use Loops?

Types of Loops in C

There are 3 main types of loops in C:

  1. for loop
  2. while loop
  3. do-while loop

1. for loop

The for loop is used when the number of iterations is known beforehand.

for (initialization; condition; update) {
    // Code to execute repeatedly
}

Example: Print numbers from 1 to 5

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

2. while loop

The while loop executes as long as the condition is true.

while (condition) {
    // Code to execute repeatedly
}

Example: Print numbers from 1 to 5

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

3. do-while loop

The do-while loop executes the code block at least once, then repeats as long as the condition is true.

do {
    // Code to execute
} while (condition);

Example: Print numbers from 1 to 5

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

Summary Table of Loop Types

Loop Type Execution Condition Check When to Use
for Known number of iterations Before each iteration When iteration count is known
while Unknown iterations Before each iteration Repeat while condition is true
do-while At least once After each iteration When code must run at least once

Practice Assignments

  1. Write a program using a for loop to print the multiplication table of 7 (from 7×1 to 7×10).
  2. Write a program using a while loop to calculate the sum of numbers from 1 to 50.
  3. Write a program using a do-while loop to repeatedly ask the user to enter a number until they enter 0.
  4. Write a program to find the factorial of a number using any loop.

Further Reading

For more detailed information, examples, and explanation on loops in C, visit the Programiz - C Loops Tutorial.