Definition: The for loop is a repetition control structure used to execute a block of statements repeatedly. It is especially useful when the number of iterations or the loop range is known in advance.
Definition: The for loop is a
repetition control structure used to execute a block of statements
repeatedly. It is especially useful when the number of iterations
or the loop range is known in advance.
for loop can be used to print numbers from
1 to 5.
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 5; i++)
printf("%d ", i);
return 0;
}
1 2 3 4 5
The for loop contains three important parts:
initialization, condition and update.
for (initialization; condition; update)
{
statements;
}
for (i = 1; i <= 5; i++):
i = 1i <= 5i++
A college application may need to process the records of a fixed
number of students. A for loop can repeat the same
operation for each student.
Write a C program to calculate the sum of natural numbers from
1 to N using a for loop.
for loop.
Initialize sum to 0 and use a for loop
from 1 to N. Add each value to
sum.
A for loop combines initialization, condition checking
and updating in a compact structure. It is commonly used when the
number of iterations is known or follows a fixed range.
#include <stdio.h>
int main()
{
int n, sum = 0; // sum stores the running total
printf("Enter N: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) // i runs from 1 to n
sum += i; // add the current value to sum
printf("Sum of first %d natural numbers = %d
", n, sum);
return 0;
}
Enter N: 10 Sum of first 10 natural numbers = 55
A common mistake is using the wrong loop condition or forgetting the update expression. Make sure the loop variable moves toward the stopping condition.
| for | while |
|---|---|
| Initialization, condition and update are written together. | Initialization and update are usually written separately. |
| Useful when the loop range is known. | Useful when repetition depends mainly on a condition. |
| Compact loop structure. | More flexible when the update logic is complex. |
for loop is used for repeated execution.| Part | Meaning |
|---|---|
| Initialization | Sets the starting value. |
| Condition | Determines whether the loop continues. |
| Update | Changes the loop variable. |
Watch a beginner-friendly explanation of the for loop in C.
A short handwritten-style revision sheet for the for loop will be provided here.
Use the mind map for quick revision of initialization, condition, execution and update.