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.

Similar Reads

Syntax of for Loop

The syntax of for loop in C++ is shown below:...

Flowchart of for Loop in C++

Flowchart of for Loop in C++...

Examples of for Loop in C++

Example 1...

C++ Nested for Loop

...

Multiple Variables in for Loop

...

C++ Infinite for Loop

...

Range-Based for Loop in C++

A nested for loop is basically putting one loop inside another loop. Every time the outer loop runs, the inner loop runs all the way through. It’s a way to repeat tasks within tasks in your program....

for_each Loop in C++

...