Multiple Variables in for Loop
In the for loop we can initialize, test, and update multiple variables in the for loop.
Example of Using Multiple Variables in for Loop
The below example demonstrates the use of multiple variables for loop in a C++ program.
C++
// C++ program to demonstrate the use of multiple variables // in for loops #include <iostream> using namespace std; int main() { // initializing loop variable int m, n; // loop having multiple variable and updations for (m = 1, n = 1; m <= 5; m += 1, n += 2) { cout << "iteration " << m << endl; cout << "m is: " << m << endl; cout << "j is: " << n << endl; } return 0; } |
Output
iteration 1 m is: 1 j is: 1 iteration 2 m is: 2 j is: 3 iteration 3 m is: 3 j is: 5 iteration 4 m is: 4 j is: 7 iteration 5 m is: 5 j is: 9
Explanation
The above program uses for loop with multiple variables (here m and n). It increments and updates both variables in each iteration and prints their respective values.
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific number of iterations.
for loop is generally preferred over while and do-while loops in case the number of iterations is known beforehand.
Contact Us