4.1k views
0 votes
What is the output of the following code?

int main() {

int x = 10; int y = 30;
if (x < 0) {
y = 0;
}
else if (x < 10) {
y = 10;
}
else {
y = 20;
}
cout << y;
return 0;
}

Select one:

a. 0
b. 10
c. 20
d. 300

1 Answer

1 vote

Answer:

c. 20

Step-by-step explanation:

The program works as following:

x is initialized to 10

y is initialized to 30

if (x < 0) statement checks if the value of x is less than 0. This condition evaluates to false because x=10 so 10 is greater than 0. So the statement inside the body of this if condition will not execute. Hence the program control moves to the else if part:

else if (x < 10) statement checks if the value of x is less than 10. This condition evaluates to false because x=10 so x is equal to 10 and not less than 10. So the program control moves to the else part and the statement in else part executes:

else {

y = 20;

}

This statement in else part assigns the value 20 to y

Then the program control moves to the following statement:

cout << y;

This statement prints the value of y. As the else part assigns 20 to y so the output is:

20

What is the output of the following code? int main() { int x = 10; int y = 30; if-example-1
User Meytal
by
4.9k points