![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Newbie
Join Date: Jul 2005
Posts: 15
Rep Power: 0
![]() |
Problem with while loop...
Hi,
I am trying to print out a number entered by user that is positive and multiples of 10... But when I compile and execute the code below, only negative numbers will loop but any positive numbers will print out... Where have I done wrong?.... int main(int argc, char *argv[])
{
int x;
printf("Welcome to Carleton Bank.\n");
printf("Please enter an amount...\n");
scanf("%d",&x);
while((x < 0) && (x % 10 != 0))
{
printf("Illegal number. Try again.\n");
scanf("%d",&x);
}
printf("%d",x);
return 0;
} |
|
|
|
|
|
#2 |
|
Hobbyist Programmer
Join Date: May 2005
Location: Indiana
Posts: 130
Rep Power: 4
![]() |
while((x < 0) || (x % 10 != 0))
{
printf("Illegal number. Try again.\n");
scanf("%d",&x);
}I think that should fix it. If you use && in this case, while() is not going to execute unless both coniditons are True. EDIT: @7LSqr: saw that too ![]() |
|
|
|
|
|
#3 |
|
PFO God In Training
![]() Join Date: Jun 2005
Location: near St Louis, MO. (USA)
Posts: 600
Rep Power: 4
![]() |
in addition to what the others said, your loop is an infinite loop -- if it executes the first time it will just sit there an execute forever because x is never changed.
|
|
|
|
|
|
#4 | |
|
Professional Programmer
Join Date: May 2005
Location: Bad Nauheim, Germany
Posts: 436
Rep Power: 4
![]() |
Quote:
__________________
-Steven "Is this a piece of your brain?" - Basil Fawlty |
|
|
|
|
|
|
#5 | |
|
Expert Programmer
Join Date: May 2005
Location: East Lansing, MI
Posts: 663
Rep Power: 4
![]() |
Quote:
|
|
|
|
|
|
|
#6 | |
|
Hobbyist Programmer
Join Date: Jun 2005
Location: here
Posts: 146
Rep Power: 4
![]() |
Quote:
(x < 0) || (x % 10 != 0) That way if either of the conditions is true the loop continues; not only if they both are true... [edit]oops...Sorry Everlearning... [/edit]
__________________
"...and though our kids are blessed their parents let them shoulder all the blame." - The Quiet Things That No One Ever Knows [BrandNew] |
|
|
|
|
|
|
#7 |
|
Newbie
Join Date: Jul 2005
Posts: 15
Rep Power: 0
![]() |
It works now after I change the AND to OR operator. Thank for pointing that out.
![]() |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|