For loop with two variables c++ – For loop with 2 variables in C++ and Java

How to create for loop with two variables in C++ and Java ?

For loop with two variables c++: For loop is used as a looping statement, and we use this for loop when we want to iterate over something.

General for() loop syntax

Syntax :  for (initialization_statement; condition_statement; update_statement)          {            Body that to be executed if the condition_statement satisfies          }

where,

  • intialize_statement executed only once.
  • condition_statement checked every time if condition satisfies then body executes.
  • update-statement refers to the increment or decrement.

But many times we have faced such a situation where we want to increment or decrement two variables.

For example I want to increment i to 10 to 15 and similarly decrement j from 15 to 10 in a single for loop.

For Loop with two variables in C++ :

For loop with two variables java: Let’s see the implementation of two variables in for loop in C++

//Program :

#include <iostream>
int main()
{
// two variables i and j
// i will increment from 10 to 15
// j will decrement from 15 to 10
for (int i = 10, j = 15; i <= 15 && j >=10; i++, j--)
{
std::cout << "i = " << i << " :: " << "j = " << j << std::endl;
}
return 0;
}

 

Output :
i=10 : j=15
i=11 : j=14
i=12 : j=13
i=13 : j=12
i=14 : j=11
i=15 : j=10

For Loop with two variables in Java :

C++ for loop with multiple variables: Let’s see the implementation of two variables in for loop in C++

//Program :

public class Main {
    public static void main(String[] args) {
// two variables i and j
// i will increment from 10 to 15
// j will decrement from 15 to 10
        for (int i = 10, j = 15; i <= 15 && j >= 10; i++, j--) {
            System.out.println("i = " + i + " :: " + "j = " + j);
        }
    }
}
Output :
i=10 : j=15
i=11 : j=14
i=12 : j=13
i=13 : j=12
i=14 : j=11
i=15 : j=10