tags:

views:

211

answers:

4
do
{
    printf("Enter number (0-6): ", "");
    scanf("%d", &Num);
}while(Num >= 0 && Num <=6);

any ideas?

+3  A: 
Mark Rushakoff
nope, I used int like you have but as a global variable
tom
it seems to be repeating the code if the number is between 0 and 6 - but if i reverse the > to < then it still doesnt work :S
tom
@tom: It's supposed to repeat as long as the number is between 0 and 6.
SLaks
but even still, if i need to input something between 0 and 6, and I enter 90, it'll just skip the loop
tom
@tom: that's how a (do) while loop is *defined* to work. What's the behavior you *expect*? The code is doing what you *told* it to do, but probably what you told it is not what you meant :) That's probably the most common programming mistake, of course.
Mark Rushakoff
A: 

Maybe you need to add a getchar after scanf to remove '\n' from keyboard buffer:

do
{
    printf("Enter number (0-6): ", "");
    scanf("%d", &Num);
    getchar();
} while(Num >= 0 && Num <=6);

Hope it helps.

Pablo Santa Cruz
+5  A: 

You're misunderstanding your loop.

Your code is read like this:

Do something While (as long as) num is more than (or equal to) zero And num is less than (or equal to) six

The C compiler is listening to your code and doing exactly what you are (mistakenly) telling it to, which is to keep looping as long as the number is between 0 and 6.

You actually want it to keep looping as long as the number is not between 0 and 6, so you actually want the code to look like this:

Do something While num is less than zero Or num is more than six

Once the user enters a number that is between 0 and 6, the code will see that num is neither less than 0 and nor more than 6, so it will stop the loop. (Because the condition will be false)

You should be able to code that yourself.
Hints: > means 'more than', < means 'less than', and || means 'or'.

SLaks
do you mean `||`?
Potatoswatter
I can't believe I wrote that. Fixed.
SLaks
A: 

This code is working fine with me, I have run your program, user can only enter the values from 0 to 6, do while work in this range, on other values loop break.

Arman