Open In App

Output of C programs | Set 56 (While loop)

Improve
Improve
Like Article
Like
Save
Share
Report

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




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


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?




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


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?




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


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?




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


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?




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


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

Answer : a 

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



Last Updated : 25 Sep, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads