Skip to content

Back to module

6. While Loop


Q) While: What prints 12?

Consider the following code fragment.

CPP
int x = ???;
int sum = 0; 
while (x > 0) {
    if (x % 2 == 0) {
        sum += x;
    }
    x--;
}
cout << sum << endl;

What value should x be initialized to in order for it to print out 12?

a) 3
b) 5
c) 7
d) 9


Answers

c) 7