← Back to C Course | Chapter 4: Control Flow | Lesson 9 of 11

C for Loop

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?

c
#include <stdio.h>
int main() {
	for (int i = 0; i < 3; i++) {
		printf("%d ", i);
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	for (int i = 1; i <= 5; i++) {
		printf("%d ", i);
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	for (int i = 0; i <= 10; i += 2) {
		printf("%d ", i);
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int sum = 0;
	for (int i = 1; i <= 5; i++) {
		sum += i;
	}
	printf("%d", sum);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	for (int i = 5; i >= 1; i--) {
		printf("%d ", i);
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.