![]() |
VOOZH | about |
In C programming, the 'for' loop is a control flow statement that is used to repeatedly execute a block of code as many times as instructed. It uses a variable (loop variable) whose value is used to decide the number of repetitions. It is commonly used to iterate over a sequence such as an array or list.
Hi Hi Hi Hi Hi
Explanation: In this example, the loop prints the text "Hi" 5 times. The loop variable i is initialized to 1. The condition i <= 5 is checked before each iteration. After each iteration, i is incremented by 1. So this loop was executed 5 times.
where,
Note: As we can see, unlike the while loop and do…while loop, the for loop contains the initialization, condition, and updating statements for loop as part of its syntax.
The working of for loop is mentioned below:
- Step 1: Initialization is the basic step of for loop this step occurs only once during the start of the loop. During Initialization, variables are declared, or already existing variables are assigned some value.
- Step 2: During the Second Step condition statements are checked and only if the condition is the satisfied loop we can further process otherwise loop is broken.
- Step 3: All the statements inside the loop are executed.
- Step 4: Updating the values of variables has been done as defined in the loop.
Continue to Step 2 till the loop breaks.
The following flow chart defines the logic behind the working of for loop.
The below examples demonstrate the use of for loop in different cases:
1 2 3 4 5
We have not used braces {} in the body of the loop in this program. Actually, the braces {} can be skipped if there are only one statement in the loop.
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Explanation: This code uses nested for loops to generate a multiplication table up to 5. The outer loop iterates through the rows (from 1 to 5), and the inner loop (controlled by j) iterates through the columns (also from 1 to 5). For each combination of i and j, the product i * j is printed, creating the table entries.
This is a kind of for loop where the input parameters are not available or the condition that's always true due to which, the loop iterates/runs endlessly.
Output
GfG
GfG
.
.
.
infinity