C Loops
for Loop
The for loop is used when the number of iterations is known. It has three parts: initialization, condition, and update expression.
for (initialization; condition; update) {
// body
}
while Loop
The while loop checks the condition before each iteration. If the condition is false initially, the body never executes.
while (condition) {
// body
}
do-while Loop
The do-while loop executes the body at least once, then checks the condition. Useful for menu-driven programs.
do {
// body (executes at least once)
} while (condition);
#include <stdio.h>
int main() {
// for loop — print 1 to 5
printf("for loop: ");
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
// while loop — print 1 to 5
printf("while loop: ");
int n = 1;
while (n <= 5) {
printf("%d ", n);
n++;
}
printf("\n");
// do-while loop — executes at least once
printf("do-while: ");
int x = 1;
do {
printf("%d ", x);
x++;
} while (x <= 5);
printf("\n");
// do-while with false condition — still runs once
printf("do-while (false condition): ");
int y = 10;
do {
printf("%d ", y); // prints 10 even though 10 > 5
} while (y <= 5);
printf("\n");
return 0;
}
/*
Output:
for loop: 1 2 3 4 5
while loop: 1 2 3 4 5
do-while: 1 2 3 4 5
do-while (false condition): 10
*/
#include <stdio.h>
int main() {
// Print 5x5 multiplication table
printf("Multiplication Table (5x5):\n");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%4d", i * j);
}
printf("\n");
}
// Print a right triangle pattern
printf("\nRight Triangle:\n");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
/*
Multiplication Table (5x5):
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Right Triangle:
*
* *
* * *
* * * *
* * * * *
*/
#include <stdio.h>
int main() {
// break — exits the loop immediately
printf("break (stop at 5): ");
for (int i = 1; i <= 10; i++) {
if (i == 6) break;
printf("%d ", i);
}
printf("\n");
// continue — skips current iteration, continues loop
printf("continue (skip evens): ");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
printf("%d ", i);
}
printf("\n");
// goto — jumps to a label (use sparingly!)
int count = 0;
loop_start:
if (count < 5) {
printf("goto count: %d\n", count);
count++;
goto loop_start;
}
printf("Done.\n");
return 0;
}
/*
Output:
break (stop at 5): 1 2 3 4 5
continue (skip evens): 1 3 5 7 9
goto count: 0
goto count: 1
goto count: 2
goto count: 3
goto count: 4
Done.
*/
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.