ODP - 1 year ago 46

C++ Question

When I try to solve this problem I write the following code:

`int x = 1;`

while(x%2 != 0 && x <= 50) { //x%2 != 0 defines odd integers and x<=50 gives the first 25

cout << pow(x,0.5) << endl;

x = x + 1;

}

This code only prints out the value of the square root of 1. So I edit the code like so:

`int x = 1;`

while(x%2 != 0 && x <= 50) {

cout << pow(x,0.5) << endl;

x = x + 2;

}

Now it prints out the all 25 odd integer square roots.

So the problem with the first code is clearly that the while loop is stopping once the square root cannot be executed (i.e. when the integer is even). It is executing the square root of 1, moving on to the integer 2, not executing the square root, and instead of then moving onto the integer 3 it is stopping. This is why the second code works: because I am adding 2 it is only ever meeting an odd integer, so always works and thus continues until x<=50.

How can I stop it from stopping and why is it doing this? I would have thought that it would register each and every integer that satisfies the condition but it is not doing this.

Answer Source

`while`

executes while the condition is `true`

. On the second iteration `x == 2`

, so the condition `x%2 != 0`

becomes `false`

, consequently `x%2 != 0 && x <= 50`

becomes `false`

and `while`

loop terminates.

You already solved *How can I stop it from stopping* part by incrementing `x`

by 2, so it's unclear what you are asking here.