This thing won't loop.

#include <iostream>
using namespace std;

So I'm going through this book on C++ and I got to this point with loops. It asked me to write a program that, if you give it a number that isn't a choice on the list, it's SUPPOSED to loop and give you the list again. But it doesn't. Why is this?

I tried making the && into || but it makes the program not do anything. Why is this? Thanks in advance.

int main ()

{
int choice=0;
while (choice<1 && choice>2);
{
cout<<"1. Hi\n";
cout<<"2. Bye\n";
cin>>choice;
}
if (choice==1)
cout<<"You said Hi!";
if (choice==2)
cout<<"You said Bye!";
}

PS: Okay, here's another one... This one jumps straight into giving a total of 0. It's not even acknowledging the loop...

#include <iostream>
using namespace std;

int main ()

{
int runningsum = 0;
int userinput = 0;
while (userinput != 0)
{
cout<<"Enter a number:"<<endl;
cin >> userinput;
cin.ignore();
runningsum = runningsum + userinput;
cout << runningsum;
}
cout<<"Your total is: "<<runningsum;
}
Last edited on
on the first one it will only do the loop if its greater than two AND less than one. switch the signs. the second is because userinput is initialized to zero make it something else
In the first one, there are 2 problems:

while(choice<1 && choice>2)

means "Execute this block of code while choice is less than 1 AND choice is greater than 2"

Choice is never going to be both of those things, so the block is never go to be executed.

The second problem is that after
while(...)
you have a semicolon ;

This ends the loop completely.

Here is an example of using a semicolon with a while loop:

1
2
while(count < 10)
    count++;


The statement that ends with a semicolon straight after the while loop is executed while count is less than 10. Because, in your case, there is a semicolon on its own, nothing will be executed (even when you do change && (meaning AND) to || (meaning OR)).

___________________________________________

In the second one, you give userinput the value 0. However, the block of code after the while() is only executed if userinput is not equal to 0.

A solution to this is to either not give userinput a value (which is a bad idea, as it means the value is undefined and could be anything) or to give it another value (eg. 1), since the user enters a new value before anything is done to it.

An even better idea would be to change the loop from

1
2
3
4
while(userinput != 0)
{
    ...
}


to

1
2
3
4
do
{
    ...
} while(userinput != 0);


This means that the value of userinput is only checked after the loop has been executed for the first time (which is what you want).
Last edited on
Topic archived. No new replies allowed.