For Loops
Lesson 24Author : Afrixi
Last Updated : January, 2023
For loops are used in C to repeat a block of code a specific number of times. The syntax for a for loop in C is as follows:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Here’s what each part of the for loop does:
-
initialization
: This is where you set the initial value for the loop variable. It is executed once before the loop starts. -
condition
: This is a boolean expression that is evaluated at the beginning of each iteration of the loop. If it is true, the loop continues. If it is false, the loop ends. -
increment/decrement
: This is where you update the loop variable at the end of each iteration of the loop. It is executed at the end of each iteration.
Here’s an example of a for loop that prints the numbers from 1 to 10:
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
In this example, i is the loop variable that is initialized to 1, the condition is i <= 10
, and i
is incremented by 1 at the end of each iteration.
The output of this code will be:
1 2 3 4 5 6 7 8 9 10
You can also use a for loop to iterate through an array. Here’s an example that sums the elements of an array:
int array[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += array[i];
}
printf("The sum is %d", sum);
In this example, i
is used as the loop variable to index into the array. The condition is i < 5
, which ensures that the loop only runs for the length of the array. The loop variable i
is incremented by 1 at the end of each iteration. The sum variable is used to accumulate the sum of the elements in the array.
The output of this code will be:
The sum is 15