Given positive integer numInsects, write a while loop that prints that number doubled without reaching 100. Follow each number with a space. After the loop, print a newline. Ex: If numInsects = 8, print:

8 16 32 64

#include

using namespace std;

int main() {

int numInsects = 0;

numInsects = 8; // Must be >= 1

while (numInsects < 100) {

numInsects = numInsects * 2;



cout << numInsects << " ";

}

cout << endl;

return 0;

}

So my question is what am I doing wrong?

Respuesta :

Answer:

The cout<<numInsects<<""; statement should be placed before numInsects = numInsects * 2;  in the while loop.

Explanation:

Your program gives the following output:

16  32  64  128

However it should give the following output:

8  16  32  64

Lets see while loop to check what you did wrong in your program:

The while loop checks if numInsects is less than 100. It is true as numInsects =8 which is less than 100.

So the body of while loop executes. numInsects = numInsects * 2;  statement in the body multiplies the value of numInsects i.e 8 with 2 and then cout << numInsects << " ";  prints the value of numInsects  AFTER the multiplication with 2 is performed. So 8 is not printed in output but instead 16 (the result of 8*2=16) is printed as the result of first iteration.

So lets change the while loop as follows:

while (numInsects < 100) {

cout << numInsects << " ";

numInsects = numInsects * 2;

Now lets see how it works.

The while loop checks if numInsects is less than 100. It is true as numInsects =8 which is less than 100

So the body of while loop executes. cout << numInsects << " "; first prints the value of numInsects i.e. 8. Next numInsects = numInsects * 2;  multiplies the value of numInsects i.e 8 with 2. So first 8 is printed on the output screen. Then the multiplication i.e. 8*2=16 is performed as the result of first iteration. So now value of numInsects becomes 16.

Next the while loop condition numInsects < 100 is again checked. It is true again as 16<100. Now cout << numInsects << " "; is executed which prints 16. After this, the multiplication is again performed and new value of numInsects becomes 32 at second iteration. This is how while loops continues to execute.

So this while loop stops when the value of numInsects exceeds 100.

Ver imagen mahamnasir