Friday 7 June 2013

Loop Question 1

What will be output of following c code?

#include<stdio.h>
extern int x;
int main(){
    do{
        do{
             printf("%o",x);
         }
         while(!-2);
    }
    while(0);
    return 0;
}
int x=8;



EXPLANATION


Output: 10
Explanation:
Here variable x is extern type. So it will search the definition of variable x. which is present at the end of the code. So value of variable x =8
There are two do-while loops in the above code.  AS we know do-while executes at least one time even that condition is false.  So program control will reach  at printf statement at it will print octal number 10 which is equal to decimal number 8.
Note: %o is used to print the number in octal format.
In inner do- while loop while condition is ! -2 = 0
In C zero means false.  Hence program control will come out of the inner do-while loop.   In outer do-while loop while condition is 0. That is again false. So program control will also come out of the outer do-while loop.

No comments:

Post a Comment