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:
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.
Last updated