could anyone help me understand this code? http://dpaste.com/767989/ The value of x is 20.Could anyone tell me why?
Let us start from here: int x=0; ---------> sets value of x to 0 while ( x <=10 ) -----------------> a loop that runs for condition that x is < 10 for ( ; ; ) -------------------> this is an infinite for loop. if ( ++x % 10== 0 ) ---------> pre-incrementing x/checking for multiple of 10 break; ---------------------> if so break out of the loop printf("x= %d\n", x); -------------------> print value of x Now for the logical explanation: At the first step x is set to 10. consider the two loops. If you know how nesting of loops occur (which I am assuming you don't) you'll know that first the inner loop (int this case the for loop) first completes, then the outer loop (yup, you guessed it right, it's the while loop) completes. So the for loop with no conditions inside (;;) means an infinite loop and for that the break statement has been provided to break out of the loop. so after 10 iterations ++x made x=10, where the for loop terminates, and condition jumps to while loop, which mentions x can be equal to 10, so again the for loop operates, making x= 20 and then the code terminates, with 20 as answer. Hope you got it !
Got it Thanks!
Welcome !
Join our real-time social learning platform and learn together with your friends!