differences between using "while" and "if"
i get the feeling that you are not clear of the difference between if statements and while loops, so i've written the following with that in mind, hope it clears the issue up for you. the following is obviously not real code, don't try to compile it!
I assume that you are trying to use loops for running the program over and over again at will. if not, then use if statements like the previous post said, or remove the while loop from the code below. here what i think you were trying to do, and i know its not a very eloquent solution, but the aim of writing the code like this is to show how to apply if statements to the situation correctly.
just for some clarity for you, i will describe what happens here. when the program starts, it enters a while loop. the purpose of initializing choice = 1 is for this - any non zero number will do. then the user is asked to choose what they want to do by entering 1 for toys, 2 for food or 0 to quit.
assuming they choose 1, then choice is set to 1. the first thing the computer sees after that is
if (choice == 1)
since choice is 1, the computer knows to execute the following code block (for the toys). after it has finished this, the computer then sees
if (choice == 2)
but you haven't changed the value of choice, so the if statement is false - the computer won't execute that block of code - it skips on. there is nothing after that block of code, so the end of the loop is reached. this causes the computer to "jump" back up to where is says
while (choice != 0)
but like i said before, choice is still 1. this means that the looping condition is true, so the loop begins again. then you are asked to make a choice again - 1, 2 or 0. so long as you dont pick 0, you can loop over as many times as you like. this is not an infinite loop though, because you can easily enter 0 and break the loop.
try removing the while loop - the program will run once (because if statemnts only run once on their own) and then exit. try changing the while loop to something like:
while (2 > 1)
you get an infinite loop - no matter what you choose, the code loops over! That is essentially what you had done in your 2 loops, there was no way of breaking the looping conditions.
i hope that this provides some insight and helps you out, and i apologise if i made it overly long and detailed, just trying to cover all the angles!
Code:
#include <a bunch of header files you need.h>
int main ()
{
int declare all the variables;
int choice = 1; /*this is to allow the program to enter the loop*/
while (choice != 0)
{
printf ("Make your choice - toy or food (or quit): ");
scanf ("%d", &choice);
if (choice == 1)
{
/*do the stuff relating to toys*/
...
}
if (choice == 2)
{
/*do stuff relating to food*/
...
}
} /*end of the while loop*/
return 0;
}