Prerequisite : While loops
Q.1 What is the output of this program?
CPP
Option
a) 3 2 1 0
b) 2 1 0 -1
c) infinite loop
d) -65535
CPP
option:- a
a) 3 2 1 0
b) 2 1 0 -1
c) infinite loop
d) -65535
CPP
option
a) 1
b) 0
c) -1
d) infinite
CPP
option
a) 0
b) 1
c) -1
d) infinite
CPP
#include <iostream>
using namespace std;
int main()
{
unsigned int x = 3;
while (x-- >= 0) {
printf("%d ", x);
}
return 0;
}
Answer : CExplanation: 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;
}
Answer: bExplanation: 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;
}
Answer : CExplanation 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;
}
Answer: bExplanation: 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 : aExplanation: The inner printf executes and print some garbage value.