Important Concept

Multiple Conditions in a for() Loop

In a for loop, multiple conditions can be initialized. These conditions need to be separated by using the comma (,) operator. Let us see how multiple conditions can be declared inside a for loop.

Syntax

  for (i = 0, j = 0; i < 6, j < 5; i++, j++)
    {
      // print i and j
    }

In the above example, two conditions were specified inside the for loop. One condition is i<6 and the other condition is j<5. For the first condition i<6, the output printed should be 0, 1, 2, 3, 4, 5 and for the second condition j<5 the output printed should be 0, 1, 2, 3, 4.

However, the loop will run as long as both the conditions are true. This means that the loop will stop as soon as one of the conditions become false, that is, when j becomes 5, thus, the output for both i and j will be 0, 1, 2 , 3, 4.

Let us see the programmatic representation of multiple conditions inside a for loop.

C Program

#include <stdio.h>
void main ()
{
  int i, j;
  for (i = 0, j = 0; i < 6, j < 5; i++, j++)
    {
      printf ("i = %d\t  j = %d\n", i, j);
    }
}

Output

i = 0	    j = 0
i = 1	    j = 1
i = 2	    j = 2
i = 3	    j = 3
i = 4	    j = 4

C++ Program

#include <iostream>
using namespace std;
int main ()
{
  int i, j;
  for (i = 0, j = 0; i < 6, j < 5; i++, j++)
    {
      cout << "i = " << i << "\t" << "j = " << j << "\n";
    }
  return 0;
}

Output

i = 0	    j = 0
i = 1	    j = 1
i = 2	    j = 2
i = 3	    j = 3
i = 4	    j = 4

Java Program

class Main
{
  public static void main (String[]args)
  {
    for (int i = 0, j = 0; (i < 6 & j < 5); i++, j++)
      {
	System.out.println ("i = " + i + " j = " + j);
      }
  }
}

Output

i = 0	    j = 0
i = 1	    j = 1
i = 2	    j = 2
i = 3	    j = 3
i = 4	    j = 4

Javascript Program

for (var i = 0, j = 0; i < 6 && j < 5; i++, j++)
  {

    console.log ("i = " + i + " j = " + j);

  }

Output

i = 0	    j = 0
i = 1	    j = 1
i = 2	    j = 2
i = 3	    j = 3
i = 4	    j = 4

Conclusion

In this article, we have learned multiple conditions inside a for loop, and how to implement it in c, c++, java, and javascript.

Aniket Malik

Aniket Malik

CERTIFIED TUTOR/TRAINER WITH 300+ REVIEWS

Facing difficulty with

this concept?