Thursday, November 20, 2008

Output for both the programs is different when the logic is same

61.How come the output for both the programs is different when the logic is same?

main( )
{
int i, j ;
for ( i = 1, j = 1 ; i <= 5, j <= 100 ; i++, j++ )
{
gotoxy ( 1, 1, ) ;
printf ( "%d %d", i, j ) ;
}
}
main( )
{
int i, j ;

for ( i =1, j = 1; j <= 100, i <= 5; i++, j++ )
{
gotoxy ( 1, 1 ) ;
printf ( "%d %d", i, j ) ;
}
}
Output -> 5 5
Even if logic of both the programs is same the output of the first program comes out to be 100, 100, but of the second program it is 5, 5. The comma operator plays a vital role inside the for loop. It always considers the value of the latest variable. So, at the time of testing the condition in for loop, the value of j will be considered in the first program and value of i in the second.

No comments:

Blog List