45.4k views
2 votes
What initial value of num would prevent cnt from being incremented three times or more in the following code?

int main() {

int cnt = 10; int num = 1;

do {

cnt = cnt + 1;

num = num - 1;

} while (num != 0);

cout << cnt;

return 0;

}

Select one:

a. No such value
b. 0
c. 2
d. 4

User Doug Ayers
by
5.3k points

1 Answer

4 votes

Answer:

c. 2

Step-by-step explanation:

With num initialized to the value 2, the cnt variable will not be incremented three or more times. Lets see how the program works with num=2

cnt = 10

num = 2

The do while loop first increments cnt by 1

cnt = cnt + 1;

cnt = 10 + 1

cnt = 11

Then the value of num is decremented to 1:

num = num - 1;

num = 2 - 1

num = 1

Hence cnt = 11 and num = 1

Then while (num != 0); checks if value of num is not equals to 0. This evaluates to true because num=1

At next iteration:

The do while loop first increments cnt by 1

cnt = cnt + 1;

cnt = 11 + 1

cnt = 12

Then the value of num is decremented to 1:

num = num - 1;

num = 1 - 1

num = 0

Hence cnt = 12 and num = 0

Then while (num != 0); checks if value of num is not equals to 0. This evaluates to false because num=0. So the loop breaks.

cout << cnt; statement is executed next which prints the value of cnt. Hence the output is:

12

This means that the value of num initialized to 2 does not let the cnt variable to increment more than 2 times.

User JohnnyDH
by
5.4k points