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; }
#include <iostream>
using std::cout;
using std::endl;
int main()
{
/*{
int x = 1;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}
In the above code, the initial value is x = 1
the step of changing the x variable is 2 (x = x + 2).
The variable x will take odd values: 1,3,5,7,9,11,13...
The condition (x != 12) will always be true and, accordingly, the cycle is endless.
For correct operation, it is necessary to change the initial value by changing x to
x =2
*/
int x = 2;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}
return 0;
}
Comments
Leave a comment