For loop with 2 variables in C++ and Java

In this article we will discuss how to use for loop with two variables.

For loop is basic feature we use in programming. In it we use a variable and keep on increasing or decreasing it till a condition is matched.

But many times a scenario comes where we want to increment or decrement two variables instead of one.

For example, I want to do for loop with 2 variable i.e.

Advertisements
  • i that will increment from 0 to 9
  • j that will decrement from 10 to 1

Here condition till which loop will run is (i < 10 && j > 0)

Let’s see how to do that,

For Loop with two variables in C++

#include <iostream>

int main()
{
	// for loop with two variable i & j
	// i will start with 0 and keep on incrementing till 10
	// j will start with 10 and keep on decrementing till 0

	for (int i = 0, j = 10; i < 10 && j > 0; i++, j--)
	{
		std::cout << "i = " << i << " :: " << "j = " << j << std::endl;
	}
	return 0;
}

 

For Loop with two variables in Java

public class forloop {

	public static void main(String[] args) {
		// for loop with two variable i & j
		// i will start with 0 and keep on incrementing till 10
		// j will start with 10 and keep on decrementing till 0

		for (int i = 0, j = 10; i < 10 && j > 0; i++, j--) {
			System.out.println("i = " + i + " :: " + "j = " + j);
		}

	}

}

Output for the above programs is,
i = 0 :: j = 10
i = 1 :: j = 9
i = 2 :: j = 8
i = 3 :: j = 7
i = 4 :: j = 6
i = 5 :: j = 5
i = 6 :: j = 4
i = 7 :: j = 3
i = 8 :: j = 2
i = 9 :: j = 1

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

1 thought on “For loop with 2 variables in C++ and Java”

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top