What will the following program segments print a int x 1 wh
What will the following program segments print?
a)
int x = 1;
while (x < 10);
x = x + 1;
cout << x;
b)
int x = 1;
while (x < 10)
x = x + 1;
cout << x;
c)
for (int count = 1; count <= 10; count++)
{
cout << ++count << “ “;
}
Solution
a)
int x = 1;
while (x < 10); // NOTE : here while loop is ending (semicolon)
Loop only ends when x >= 10, but we are not increasing x value in loop block(empty block), so this
enters in infinite loop
x = x + 1; // outside while loop
cout << x; // outside while loop
Output: infinite loop
b)
int x = 1;
while (x < 10)
x = x + 1; // this comes inside while loop(if you do not put curly({}) braces, only one statement comes under while loop)
cout << x; // this is outside loop
So, Output: 10
c)
for (int count = 1; count <= 10; count++)
{
cout << ++count << “ “;
}
We are count value twice, so it print: 2, 4, 6, 8, 10

