- The for loop is a widely used loop structure in C that allows you to execute a block of code repeatedly for a specified number of times.
- It consists of three parts: initialization, condition, and increment/decrement.
Syntax of a for loop in C:
C
for (initialization; condition; increment/decrement) {
// code to be executed
}
Here’s a breakdown of each part:
- Initialization: It is an expression that initializes the loop control variable. It is executed only once at the beginning of the loop.
- Condition: It is a Boolean expression that is checked before each iteration. If the condition is true, the loop continues; otherwise, the loop is terminated.
- Increment/Decrement: It is an expression that updates the loop control variable after each iteration. It is executed at the end of each iteration.
Example:
C
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
Explanation:
- In this example, the loop control variable i is initialized to 1.
- The loop continues as long as i is less than or equal to 5.
- After each iteration, the value of i is incremented by 1.
- The loop executes the code block inside it (printing the iteration number) for each iteration.
Output:
Output
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Practice problems in for loop:
Problem 1: Print Numbers in a Range
Write a program that prints all the numbers from a given start value to an end value.
C
#include <stdio.h>
int main() {
int start, end;
printf("Enter the start value: ");
scanf("%d", &start);
printf("Enter the end value: ");
scanf("%d", &end);
for (int i = start; i <= end; i++) {
printf("%d ", i);
}
return 0;
}
Explanation:
- The program takes input from the user for the start and end values.
- The for loop is used to iterate from the start value to the end value.
- The loop control variable i is initialized to the start value, and the loop continues as long as i is less than or equal to the end value.
- In each iteration, the value of i is printed.
- The loop iterates until i reaches the end value.
Output
Enter the start value: 5
Enter the end value: 9
5 6 7 8 9