Home / Programs / for loop with multiple test conditions
Programming Example

for loop with multiple test conditions

👁 3,147 Views
💻 Practical Program
📘 Step by Step Learning
We can have multiple initializations in the for loop as shown below. for (i=1,j=1;i<10 && j<10; i++, j++)

Program Code

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

Output

1, 1
2, 2
3, 3
4, 4
Press any key to continue . . .

Explanation

Multiple initialization inside for Loop in C

We can have multiple initialization in the for loop as shown below.

for (i=1,j=1;i<10 && j<10; i++, j++)

What’s the difference between above for loop and a simple for loop?
1. It is initializing two variables. Note: both are separated by comma (,).
2. It has two test conditions joined together using AND (&&) logical operator. Note: You cannot use multiple test conditions separated by comma, you must use logical operator such as && or || to join conditions.
3. It has two variables in increment part. Note: Should be separated by comma.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.