About C 'for' Loop
In C programming, 'for' loop is used to efficiently iterate for a specified number of times. It is a control flow statement that is used to repeatedly execute a block of code while iterating over a sequence.
It is typically used when you know in advance how many times you want to execute a block of code.
Syntax of 'for' loop
-
for: The 'for' keyword begins the 'for' loop. -
initialization: It is used to initialize a loop variable which is used in loop condition. For example,int i = 1;initializes an integer variable 'i' with 1 value. -
condition: The condition of the loop is specified here. The condition is evaluated before each iteration of the loop. For example,i <= 5;specifies that the loop will continue as long as 'i' is less than or equal to 5. -
update: After each iteration of the loop, it is typically used to update the value of loop variable. For example, 'i++increments 'i' variable by 1 after each iteration. -
block of code to be executed: This is the block of code (body of loop) enclosed in curly braces {}. The code will be executed repeatedly as long as the condition remains true.
Create a 'for' loop statement
A 'for' loop statement has been created in the following example that will print number from 1 to 5:
Example of 'for' loop
Output of the above example
1 2 3 4 5
Explanation of code:
-
for: The 'for' keyword begins the 'for' loop. -
int i = 1;: This part declares an integer variable named 'i' and initializes the variable by assigning value 1 to the variable. It will be used in the condition. -
i <= 5;: The condition of the loop is specified here. 'i <= 5;' specifies that the loop will continue as long as 'i' is less than or equal to 5. The condition is evaluated before each iteration of the loop. -
i++;: It increments the value of the 'i' variable by 1. -
printf("%d\n", i);: The line prints the value of 'i' variable. '%d' is the format specifier of integer data and '\n' creates a newline. It is the body of the 'for' loop.