A for loop repeats a block of code while its loop condition remains true. It is especially useful when the initialization, condition and update can be written together.
for (initialization; condition; update) {
// statements repeated by the loop
}
#include <stdio.h>
int main(void) {
for (int i = 0; i <= 3; i++) {
printf("%d\n", i);
}
return 0;
}
Output
0
1
2
3
The variable i is declared inside the for statement, so its scope is limited to the loop.
break ends the loop immediately. continue skips the remaining statements in the current iteration and moves to the update step.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
printf("%d\n", i);
}
return 0;
}
Output
1
2
Change only break to continue:
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("%d\n", i);
}
return 0;
}
Output
1
2
4
5
#include <stdio.h>
int main(void) {
for (int i = 0; i <= 25; i += 5) {
printf("%d\n", i);
}
return 0;
}
Output
0
5
10
15
20
25
#include <stdio.h>
int main(void) {
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 4; column++) {
printf("(%d,%d) ", row, column);
}
printf("\n");
}
return 0;
}
Use different variable names for nested loops so the code is easier to read and the outer-loop value is not hidden.
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "plus2net";
size_t length = strlen(text);
for (size_t i = length; i > 0; i--) {
putchar(text[i - 1]);
}
putchar('\n');
return 0;
}
Output
ten2sulp
Key correction: the last printable character is at length - 1. Starting at length would first access the terminating null character.
n.n.n.n.n.Practice string patterns using for loops
The original tutorial demonstrated that a loop-control variable declared outside the for statement is still available after the loop and contains the value that caused the loop condition to become false.
#include <stdio.h>
int main(void) {
int i;
for (i = 0; i <= 5; i++) {
printf("i = %d\n", i);
}
printf("You came out of the loop.\n");
printf("i = %d\n", i);
return 0;
}
Output
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
You came out of the loop.
i = 6
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.