Output of C programs | Set 56 (While loop)

Prerequisite : While loops
Q.1 What is the output of this program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
int main()
{
    unsigned int x = 3;
    while (x-- >= 0) {
        printf("%d  ", x);
    }
    return 0;
}

chevron_right


Option
a) 3 2 1 0
b) 2 1 0 -1
c) infinite loop
d) -65535

Answer : C

Explanation: Here x is an unsigned integer andit can never become negative. So the expression x–>=0 will always be true, so its a infinite loop.



Q.2 What is the output of this program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
int main()
{
    int x = 3, k;
    while (x-- >= 0) {
        printf("%d  ", x);
    }
    return 0;
}

chevron_right


option:- a
a) 3 2 1 0
b) 2 1 0 -1
c) infinite loop
d) -65535

Answer: b 

Explanation: Here x is an integer with value 3. Loop runs till x>=0 ; 2, 1, 0 will be printed and after x>=0, condition becomes true again and print -1 after false.

Q.3 What is the output of this program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
int main()
{
    int x = 0, k;
    while (+(+x--) != 0) {
        x++;
    }
    printf("%d  ", x);
    return 0;
}

chevron_right


option
a) 1
b) 0
c) -1
d) infinite

Answer : C 

Explanation Unary + is the only dummy operator in c++. So it has no effect on the expression.

Q.4 What is the output of this program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
int main()
{
    int x = -10;
    while (x++ != 0)
        ;
    printf("%d  ", x);
    return 0;
}

chevron_right


option
a) 0
b) 1
c) -1
d) infinite

Answer: b 

Explanation: The semicolon is after the while loop. while the value of x become 0, it comes out of while loop. Due to post-increment on x the value of x while printing becomes 1.

Q.5 What is the output of this program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
int main()
{
    while (1) {
        if (printf("%d", printf("%d")))
            break;
        else
            continue;
    }
    return 0;
}

chevron_right


option
a) Garbage value
b) 1
c) 0
d) Error

Answer : a 

Explanation: The inner printf executes and print some garbage value.

This article is contributed by Gyayak Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up