For loop in c programming
For Loop loop in c
The "for" loop in C programming is a control flow statement that allows you to repeatedly execute a block of code for a specific number of times. Its syntax is as follows:
for loops is an iterative control statement
for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
The "for" loop consists of three parts:
- Initialization: Here, you initialize a loop control variable and set an initial value.
- Condition: It specifies the condition that needs to be evaluated for each iteration. If the condition evaluates to true, the loop continues; otherwise, it terminates.
- Increment/Decrement: It specifies how the loop control variable should be modified after each iteration. It can be incremented or decremented.
The "for" loop works in the following way:
- The initialization part is executed first.
- The condition is checked. If it is true, the code inside the loop is executed. If it is false, the loop is terminated.
- After executing the code inside the loop, the increment/decrement part is executed.
- The condition is checked again, and the process repeats until the condition becomes false.
Here's an example that prints the numbers from 1 to 5 using a "for" loop:
Program 01:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output: 1 2 3 4 5
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, i is incremented by 1 (i++).
You can modify the initialization, condition, and increment/decrement parts of the "for" loop to suit your specific requirements.