while
Problem:
Write a program that will sum up a series of positive values entered by the user. The program will ask the user to enter numbers and sum them up until the user enters a 0 or negative value. It will display the total at the end.
What we need to learn:
- How to do something over and over until a condition is met.
- look at while() statement.
Flow chart of problem
In the flowchart below, we see arrows (highlighted in red) where if we follow them would form a loop back into the decision box. This is a sign that an iteration type of control structure is needed
Implementation
Like all programs before, we implement by simply following the flow chart:
int main(void){
int total=0; //first box, need a total we can keep adding to
int number; //need a variable for reading
printf("please enter a number: "); //print and scan for second
scanf("%d",&number); //box
while(number > 0){ //this while statement is the decision box
//contents between curly is the statements
//that form the "loop" (the part connected
//by red arrows)
total=total+number; //add number to total box
printf("please enter a number: "); //print and scan within
scanf("%d",&number); //the loop
}
printf("Total of numbers entered: %d\n", total); //print total box
return 0;
}
Why while?
There are three types of iteration statements, and yet here we are using while. Why did we do that instead of for or do-while.
while is the most common form iteration that you will write. In general, you can do just about everything you will need to do by using while. There are a few special cases where a do-while makes things much easier but usually you use while.
a for() statment can be made to imitate a while but in general, we use for statements for "counting" loops. In this loop, we sum a number of values but we don't know how many we will sum before hand. Nor is there already a set of numbers and we simply have to go through the set. The condition for continuing is determined only at run time by the user. Thus, this is not a counting loop and we should not use a for loop.