You are on page 1of 3

John Christian Fortus CoProg1

BSCS1

1. What’s wrong with the following while loop?

int counter = 0;
while {counter > 100} // we should use ‘()’ instead of ‘{}’
if (counter % 2 == 1) // There are missing brackets, it should be ‘if (counter % 2 == 1){…}’
cout << counter << " is odd." << endl;
else // There are missing brackets, it should be ‘else {…}’
cout << counter << " is odd." << endl; // It should be ‘<<counter << “is even” ;’
counter++ // missing ‘;’

Here’s the corrected while loop


2.Describe the output produced by these while loops:

a) int K = 5;
int I = -2;
while (I <= K) {
I = I + 2;
K- -;
cout << (I + K) << endl;
}

- The output is the same for each iteration of the while loop because the value of I is always
incremented by 2, and the value of K is always decremented by 1. Therefore, the value of ( I + K)
would be 4, 5, 6.

b) int number = 4;
while (number >= 0) // There are missing brackets ‘{}’
number- -; // There must be no space between ‘- -‘, it should be ‘number--;’
cout << number << endl;

Here’s the corrected while loop


The output shows the value of number at each iteration of the while loop. The value is
decremented by 1 on each iteration, so it starts at 4 and ends at -1.

You might also like