How would i write a while loop that displays no negative numbers???
While loop that displays no negative numbers
Collapse
X
-
Originally posted by GreatnessHow would i write a while loop that displays no negative numbers???
Savage -
Originally posted by Greatnessok so like this......
Code:int n; while (n = 0) if (n>0) cin >> n; else (n < 0) cout << " Please enter another number";
???? lol
Let's look at what your code is doing.
Code:int n; while (n = 0) if (n>0) cin >> n; else (n < 0) cout << " Please enter another number";
Now, inside the loop, you test if n is greater than 0. This would be great if n had a value...but you only cin >> a value if it's greater than 0. Huh? That doesn't make sense! How can you test its value before you get it?
Now, your else statement is incorrectly written. You cannot have else (condition) - you can only say else, or else if (condition). Also, the condition is not necessary - if a number is not greater than 0, then it must be less than 0 (or must it...what if n = 0? Consider this possibility).Comment
-
Originally posted by Greatnessok so like this......
int n;
while (n = 0)
if (n>0)
cin >> n;
else (n < 0)
cout << " Please enter another number";
???? lol
1.while(n=0)
I do see lots of errors here.If i get the program right it's supposed to be a control of input.
a.Couple of errors are here: while(n=0)
solution:instea d of using number to identify when loop will break i would rather use identifer,in this case let it be i.Secound error u cant use a single = when testing expression,u must use ==.So here is fisrt part of it:
int i=0;
while(!i)//this is nearly same as while(i==0).
I see more errors in loop construction part:(e.g)
It should be this:
while(!i)
{
//loop body
}
When u have done all this 'repairment' post so that we can move forward.
SavageComment
-
Originally posted by Greatnesshmm ok so let me try this
int n;
cout << "Enter a Number"<<endl;
cin>> n;
while (n)
if (n>0)
elseif
SavageComment
-
Originally posted by GreatnessHow would i write a while loop that displays no negative numbers???
I don't understand your requirement very much...
do you wanna display all the non negative numbers or you just want to display the non negative numbers you received.
if you wanna display all by using a while loop, just do it as follows..
int n = 0;
while(1)
std::cout<<n++< <std::endl;
but if you wanna display the non negative numbers you received, using a if-else statement is good idea.Comment
-
No,no u still have number n defined, i is just identifer.
int n,i;
//loop and it's expression
//loop body
if(n>0) i=1;
else i=0;
} //loop compound statement.
Note:this task can be done much more easier if u use do-while.Do u must use while?
SavageComment
Comment