© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

9. What is difference between for loop and while loop ?

Ans:

For loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of an iterative loop, it is recommended to use 'for' loop.

While loop: When it is not necessary to do initialization, condition check and increment/decrement in a single statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is present.

Ex - 1:  What is the output?
main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
    }
Ans:
No output
Explanation:

Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop.

Ex - 2:  What is the output?
main()
    {
       signed char i=0;
       for(;i>=0;i++) ;
       printf("%d\n",i);
    }
Ans:
            -128
Explanation:

Notice the semicolon at the end of the for loop. THe initial value of the i is set to 0. The inner loop executes to increment the value from 0 to 127 (the positive range of char) and then it rotates to the negative value of -128. The condition in the for loop fails and so comes out of the for loop. It prints the current value of i that is -128.

Ex - 3:  What is the output?
main()
   {
       unsigned char i=0;
       for(;i>=0;i++) ;
       printf("%d\n",i);
    }
Ans:
      infinite loop
Explanation:

The difference between the previous question and this one is that the char is declared to be unsigned. So the i++ can never yield negative value and i>=0 never becomes false so that it can come out of the for loop.


SLogix Student Projects
bottom