Multiple Initializations and Increments in for loop
For Complete YouTube Video: Click Here
In this class, we will try to understand Multiple Initializations and Increments in for loop.
We have already discussed the concept of for loop.
In the discussion on for loop, only one variable has been initialized and incremented in the initialization and increment part of the loop.
The image below is the example that we have covered so far.
Table of Contents
Multiple Initializations and Increments in for loop
Is it possible to Multiple Initializations and Increments?
Yes, C Compiler allows us to define Multiple Initializations and Increments in the “for” loop.
The image below is the program for Multiple Initializations and Increments.
In the above program, two variable i and j has been initialized and incremented.
A comma has separated each initialization and incrementation.
We can use as many initializations and incrementations in the “for” loop based on the requirement of the program.
The output of the program is as shown below.
1, 1
2, 2
3, 3
4, 4
As we have used multiple initialization and increments, we can use multiple conditions in the condition part of the program.
The image below is the program for the multiple conditions in the condition part of the “for” loop.
If we use multiple conditions, C Compiler will execute the program differently.
As the comma operator has an associativity of left to right, the for loop will check only the rightmost condition.
In our example, j<3 is the only condition checked.
The output of the above program is as shown below.
1, 1
2, 2
It is NOT a good practice to use multiple conditions in the conditional part of the “for” loop.