y/n code

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
//have user enter students grades
cout<<"Enter students grades";

char cont;
int myinput,y,n;
int grades[6] = {0};
do{
cin>>myinput;
if(myinput <= 5) // makes sure its in range of the array, if not it will break the code
grades[myinput]++; // increments the value at grades 0 - 5

cout << "Enter another value? y or n";
cin >> cont;

}

while(cont != 'n'); //continue till n is entered, if y is entered it asks user for more numbers
while (cont ||'y');

for(int i=0; i < 6; i++) // out put the array
cout << grades[i] << " grade(s) of (" << i << ")" << endl;

system ("pause");
return 0;
}



why isn't y working correctly??
while (cont ||'y');

Let's make this code a little easier to understand. It's the same as this:

1
2
3
while (cont ||'y')
{
};


So, the first line says to do what's in the braces as long as cont OR 'y'. Well, cont is probably true (because anything not zero is true), and 'y' is always true (because anything not zero is true), so your code says:

1
2
3
while TRUE OR TRUE, do this
{
};


So your code will always do what's in those braces. Of course, there is nothing in those braces, so you've got an infinite loop with nothing in it.

Here are the key learning points:

1) || means OR, which means the result is TRUE if the thing on the left is true, or if the thing on the right is true.

2) Anything that isn't zero is true. This means that 'y' is TRUE. Always. This means than if cont holds any value other than zero (not the symbol for zero, the actual value zero) it is true.

3) There is a big difference between a do-while and a while. You need to know the difference.


So far you've posted five times and you haven't managed to do anything for yourself. You need to go back to the basics.
Last edited on
Topic archived. No new replies allowed.