I'm having a problem trying to write a loop that tells the user to input a positive number. And if number is zero the program stops. The numbers can be no greater than 1000.
- # include <iostream>
-
using namespace std;
-
-
int main()
-
{
-
int i;
-
int num;
-
-
while (num >0)
-
{
-
cout<< "Enter a positive number:"<<endl;
-
cin>> num;
-
if (num=0)
-
{
-
cout<<"END OF PROGRAM";
-
}
-
else
-
{
-
cout<< num;
-
}
-
}
-
return 0;
-
}
Hi. So stepping through your code.
You declare an int called num and give it no initial value. This means that the compiler will arrange 4 bytes of memory space to be allocated and the value of num will be any old garbage that happens to be at that memory space at that time. Could be positive, could be negative. You just don't know. Just for now we should initialize it with a zero
The next part of your code begins a while loop with the test expression (num>0). Well we know that that is not the case because we initialized num to zero so let's test after the user has input a value which mean we use a do while loop instead:
- int num = 0;
-
do {
-
//blah blah blah
-
}
-
while (num>0);
The only problem with the rest of the code comes at this point:
You are assigning the value 0 to num which is true no matter what the value of num before this assignment. To test for zero you should use double equals:
And now your code should work.