C for Loop
In this page:
What is a for Loop?
A for loop combines a variable's initialization, its exit condition, and its update step into a single line, making the loop's entire lifecycle visible at a glance instead of scattered across separate statements.
Example: What is a for Loop?
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Standard Counter
A for loop is the natural choice whenever you already know exactly how many times you want to repeat something, since the fixed number of iterations can be baked directly into the loop's condition.
Example: Standard Counter
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Even Numbers
Adjusting a for loop's initial value and its update step (incrementing by 2 instead of 1, for example) lets you print only even numbers within a range without needing an extra if check inside the loop body.
Example: Printing Even Numbers
#include <stdio.h>
int main() {
for (int i = 0; i <= 10; i += 2) {
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Summing Sequences
An accumulator variable declared outside the loop, updated by adding the loop counter's value on each pass, is the standard pattern for summing a sequence of numbers using a for loop.
Example: Summing Sequences
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
printf("%d", sum);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Decremental For Loop
To count downward with a for loop, start the counter at a high value, use a greater-than-or-equal condition, and decrement instead of increment on each pass -- the same three-part structure, just running in reverse.
Example: Decremental For Loop
#include <stdio.h>
int main() {
for (int i = 5; i >= 1; i--) {
printf("%d ", i);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: