So far, we have used only one variable in a for loop; however, more than one variable with different end values and with different modes of increments/decrements may also be used. In a compound for expression, the variables may be separated by a comma as illustrated for i and j below.
for (int i = 0, int j = 0; i <=8, j <=10; i++, j+=2)
Note that in all the three expressions of the for loop, the statements of the two controlling variables are connected by comma operators. The limiting values and the mode of increments may also be different for the two variables. In Program, three variables m, n, and pare included in for loop with differing limiting values and different modes of increment. The control to end the loop rests with the last condition in the middle expression for loop .
Illustrates compound condition in for
#include<stdio.h> void main() { int m ,n,p, Product=0; clrscr(); printf("m\t n\t p\t Product\n"); for (m=0 ,n=0, p=2 ; m<=4, n<=8, p<9 ; m++, n +=2, p++) { Product = m*n*p; printf("%d\t %d\t %d\t %d\t\n", m, n, p, Product); } }
The expected output is given below.
As already described above, the loop terminates with the condition which is last in the middle expression, i.e., p<9 . It does not terminate at m <= 4 or for n<=8. If the same program is run again with the condition for (n=2 ,m=0,p=2 ;p<9, n<=12 ,m<=4 ;n +=2,m++, p++), i.e., interchanging the middle portion of the loop, the loop will run up to m<=4.