For Loop
Part of the Fundamentals section of Coddy's C journey — lesson 37 of 63.
The for loop is a control structure that allows you to execute a block of code repeatedly for a specific number of times.
A for loop has three components:
- Initialization (executed once before the loop starts)
- Condition (checked before each iteration)
- Update (executed after each iteration)
for (initialization; condition; update) {
// code to be executed
}Let's create a simple for loop that counts from 1 to 5:
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}After executing the above code, the output will be:
1 2 3 4 5How this works:
- First, we initialize
ito 1 - Then we check if
i <= 5(true, so we execute the loop body)
- We print the value of
i - We increment
iby 1 - We repeat steps 2-4 until the condition becomes false
Challenge
EasyCreate a program that takes an integer n from input and uses a for loop to print all numbers from 1 to n, each separated by a space.
Example output for n = 4:
1 2 3 4Make sure to include a space after each number, including the last one.
Cheat sheet
The for loop executes a block of code repeatedly for a specific number of times.
For loop syntax:
for (initialization; condition; update) {
// code to be executed
}Components:
- Initialization (executed once before the loop starts)
- Condition (checked before each iteration)
- Update (executed after each iteration)
Example - counting from 1 to 5:
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}Try it yourself
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
// Write your code here
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge