Loops help repeat actions many times without writing the same code again and again.
0
0
Loop execution flow
Introduction
When you want to print numbers from 1 to 10.
When you need to check each item in a list one by one.
When you want to keep asking a user for input until they give a valid answer.
When you want to sum all values in an array.
When you want to repeat a task a fixed number of times.
Syntax
C
for (initialization; condition; update) { // code to repeat } while (condition) { // code to repeat } do { // code to repeat } while (condition);
Initialization runs once at the start.
Condition is checked before each loop cycle (except in do-while).
Examples
This prints numbers 0 to 4 using a for loop.
C
for (int i = 0; i < 5; i++) { printf("%d\n", i); }
This prints "Hello" three times using a while loop.
C
int i = 0; while (i < 3) { printf("Hello\n"); i++; }
This prints "World" two times using a do-while loop.
C
int i = 0; do { printf("World\n"); i++; } while (i < 2);
Sample Program
This program shows how three types of loops work in C. It counts up with a for loop, counts down with a while loop, and shows do-while runs at least once.
C
#include <stdio.h> int main() { int count = 1; printf("Counting from 1 to 5:\n"); for (int i = 1; i <= 5; i++) { printf("%d\n", i); } printf("\nUsing while loop to count down from 3:\n"); int j = 3; while (j > 0) { printf("%d\n", j); j--; } printf("\nUsing do-while loop to print once even if condition false:\n"); int k = 0; do { printf("This prints once even if k is %d\n", k); k--; } while (k > 0); return 0; }
OutputSuccess
Important Notes
Loops run the code inside repeatedly as long as the condition is true.
For loops are great when you know how many times to repeat.
While loops are good when you repeat until something changes.
Do-while loops always run the code at least once.
Summary
Loops repeat code to save writing the same steps many times.
For, while, and do-while loops have different ways to control repetition.
Understanding loop flow helps you control how many times code runs.