Reputation: 17
I'm new to programming, but I searched for this topic before asking and still can't figure out what my program is doing wrong.
I have this:
int i;
do
{
i = get_int("Enter positive integer between 1-10: \n");
}
while(1>i && i<10)
I want to ask the user for a positive integer between one and ten. it doesn't accept anything less than one, which is good, but it will take anything positive. I understand how I can't do 1>i<10 since it reads it from left to right but I can't get it to recognize it has to follow both operators. What is my issue?
Upvotes: 0
Views: 232
Reputation: 310990
I want to ask the user for a positive integer between one and ten.
I think you want an integer in the range with inclusive 1 and 10.
When how will look such a condition of a valid positive integer?
It will look the following way
1 <= i && i <= 10
So the do while loop must continue its iterations while this condition is not true. So in the condition of the loop you should write a negation of the above condition
int i;
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while ( !( 1 <= i && i <= 10 ) );
If to remove the parentheses then the condition will look like
int i;
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while ( 1 > i || i > 10 ) );
Upvotes: 0
Reputation: 2930
you have been mistaken (syntax mistake
) inside the while expression
(2 mistakes their, the logic is not right and a syntnatx error with 1<i
) - see fixes inline:
int i = 0; /*its better if you initialize the i here*/
do
{
i= get_int ("Enter positive integer between 1-10: \n");
}
while((i > 1) && (i < 10));
Upvotes: 0
Reputation: 1702
Your loop condition is incorrect. You should have used logical OR instead of logical AND.
This worked for me.
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while (i<1 || i>10);
Upvotes: 0
Reputation: 153498
i can't get it to recognize it has to follow both operators.
Why would it be more applicable when the integer has to meet both criteria?
do {
....
} while(test);
When the test returns true, the input is re-tried as the loop iterates again. What is the criteria for re-trying, not what is the criteria for passing.
Input only needs to fail one of two tests to re-try: too low or too high. Hence the need for "or" (||
).
} while(i < 1 || i > 10);
Upvotes: 1
Reputation: 5766
You probably want the loop to run the loop as long as user inputs a number between 1 to 10. Your condition in the while loop isn't correct. It should be as follows -
while(i>1 && i<10); # runs as long as i is in range 1 to 10
However, If you want to break the loop as soon as the user inputs any number inside the 1 to 10
range, then you should use the following -
while(!(i>1 && i<10)); # runs as long as i is outside the range 1 to 10
Upvotes: 1