# Nesting multiple while loops does not work

I tried nesting a few `while` loops so that I could give different responses depending on the users answers. But it does not work. Entering a smaller number, say -9 immediately stops ends the program and skips the other loops. Here is the code I used:

``````int height = 0;
height = GetInt();

while (height>23)
{
printf("That number is too big! Enter a smaller number!\nHeight: ");
height = GetInt();
while (height<0)
{
printf("You entered a negative number. Enter a postive number.\nHeight: ");
height = GetInt();
}
while (height==0)
{
printf("You entered 0. Enter a larger number\nHeight: ");
height = GetInt();
}
}
``````

I managed to get it to work through the following code instead though:

``````while (height<=0 || height>23)
{
if (height>23)
{
printf("That number is too big! Enter a smaller number!\nHeight: ");
height = GetInt();
}
else if (height<0)
{
printf("You entered a negative number.\nHeight: ");
height = GetInt();
}
else if (height==0)
{
printf("You entered 0. Enter a larger number.\nHeight: ");
height = GetInt();
}
}
``````

By using nested `if` functions, the program works. Is this because once you clear the condition for a `while` loop, it does not repeat anymore?

``````while (height > 23)
{
// some code
}
``````

if `height` is initially <= 23 (for example 10 or -7), the loop continuation condition evaluates to `false` and, as a result, the loop never executes. So the first statement after the loop gets executed.

``````while (height <= 0 || height > 23)
{
// some code
}
``````

This loop executes in case height is <= 0 or > 23. However, here's a couple of points that you should probably consider

• you shouldn't be printing an info message that's followed by a newline character then the prompt "Height" in order for the grader to grade your solution correctly.

• you shouldn't reject the height 0. Rather, your program should exit immediately if the height is 0 without printing anything or building any pyramids.

• you could save yourself some lines and write the statement

``````height = GetInt();
``````

just once right before the closing brace of the outer loop.

• Ok, I understand it now. Thanks Kareem! – Lucas Oct 25 '14 at 12:12