Home Tutorials C Tutorial Loops
Loops

Loops


Control Flow: Loops in C

Loops are used to repeat a block of code multiple times. Instead of writing the same code over and over, you use a loop to automate the process, making your programs efficient and easy to maintain.

1. The for Loop

The for loop is best used when you know exactly how many times you want to repeat a block of code.

Syntax:
for (initialization; condition; increment/decrement) { ... }
for (int i = 1; i <= 5; i++) {
    printf("%d\n", i);
}

2. The while Loop

The while loop repeats as long as a condition is True. It is ideal when you don't know the exact number of iterations beforehand.

int i = 1;
while (i <= 5) {
    printf("%d\n", i);
    i++; // Don't forget to update the counter!
}

3. The do...while Loop

Similar to the while loop, but with one key difference: the code block always runs at least once because the condition is checked after the code executes.

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

Loop Control Statements

Keyword Action
break Exits the loop immediately, even if the condition is still true.
continue Skips the current iteration and jumps to the next cycle of the loop.
Student Alert: Always ensure your loop has a way to end! If the condition never becomes false, you will create an "Infinite Loop," which can cause your program to crash or freeze.

🏋️ Test Yourself With Exercises

Take our quiz on Loops to test your knowledge.

Browse Quizzes »