help with this code

please anyone help me with this questions
The following code is supposed to display the positive even numbers less than 12. That is, it will
output the numbers 2,4,6,8, and 10. However, there is a logical error in the code. Explain what the
output of the code below will be. Then write a small program including the code below and make
the necessary changes to fix the code so that it displays what it is intended to display. Ensure that
your program works correctly. Only submit the program, not the output.
Hint: Use variable diagrams to trace the program to help you find the logical error.
int x = 1;
while (x!= 12)
{
cout << x << endl;
x = x + 2;
}
OK, first thing, follow your code:

You start with x = 1, and then you keep adding 2 to x, and your termination condition happens when x = 12... here's the question. Is x ever gonna equal 12?

x = 1; //this is what you start with, now keep adding 2

3
5
7
9
11
13
15
17
...

To infinity!!!!

So you have 2 things to fix, first, start from x = 0 or 2, second, for safety, make the condition

while(x < 12)

and that's it :-)

Cheers.
Last edited on
Topic archived. No new replies allowed.