For Loop in C
A for loop in C is a control flow statement that allows code to be executed repeatedly based on a condition. The loop is particularly useful for iterating a fixed number of times or over a range of values.
The syntax of a for loop in C is as follows:
for (initialization; condition; increment) {
// Code to be executed repeatedly
}
Initialization : This is executed only once, at the beginning of the loop. It usually initializes one or more loop counters.
Condition : This expression is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If it is false, the loop terminates.
Increment : This is executed after each iteration of the loop body. It usually increments or decrements the loop counter.
Here is a simple example of a for loop in C that prints numbers from 1 to 10 :
Output :
1 2 3 4 5 6 7 8 9 10
Explanation of the Example :
Initialization : int i = 1; initializes the loop counter i to 1.
Condition : i <= 10; checks if i is less than or equal to 10. If true, the loop body executes.
Increment : i++ increments the loop counter i by 1 after each iteration.
During each iteration, printf("%d ", i); prints the current value of i. The loop continues until the condition i <= 10 is false.
Output :
Enter a no:5
The factorial is=120
Output :
enter the range:10
1
2
3
4
5
6
7
8
9
10
Sum=55
Output :
0 1 1 2 3 5 8 13 21 34 55 89
The for loop is a powerful and flexible tool in C for iterating over a range of values or executing code a fixed number of times. Understanding its syntax and variations allows you to handle many programming tasks efficiently.