Brian E. Lavender
December 17, 2014
While loop flowchart
While condition
statement
statement
etc.
End While
condition must be made to evaluate true for first loop.
keepGoing == "y"
x < 3
x < 3 && keepGoing == "y"
Declare Integer x = 3
While x > 1
Display "Hi There ", x
Set count = count - 1
End While
Output
Hi There 3
Hi There 2
etc.
What do you notice that we put before the while loop?
Declare String doAgain = "Y"
While doAgain == "Y"
Display "Hi There"
End While
Output is an infinite loop!
Hi There
Hi There
etc.
How would you fix this?
Do While flowchart
Do
statement
statement
etc.
While condition
Declare Integer x = 3
Do
Display "Hi There ", x
Set count = count - 1
While x > 1
Output is the same as the while loop!
Hi There 3
Hi There 2
Declare String keepGoing
Do
Display "Hi There "
Input keepGoing
While keepGoing == "y"
Notice how keepGoing is not preinitialized.
Hi There
y
Hi There
n
Declare Integer x = -1
Do
Display "Hi There ", x
Set count = count - 1
While x > 1
Output
Hi There -1
What happened? Why did the number go negative?
While Do big task
// Variable declarations
Declare Real sales, commission
Declare String keepGoing = "y"
// Constant for the commission rate
Constant Real COMMISSION_RATE = 0.10
While keepGoing == "y"
// Get the amount of sales.
Display "Enter the amount of sales."
Input sales
// Calculate the commission.
Set commission = sales * COMMISSION_RATE
// Display the commission
Display "The commission is $", commission
Display "Do you want to calculate another"
Display "commission? (Enter y for yes.)"
Input keepGoing
End While
While Loop with a Module
Module main()
// Local variable
Declare String keepGoing = "y"
// Calculate commissions as many
// times as needed.
While keepGoing == "y"
// Display a salesperson's commission.
Call showCommission()
// Do it again?
Display "Do you want to calculate another"
Display "commission? (Enter y for yes.)"
Input keepGoing
End While
End Module
// The showCommission module gets the
// amount of sales and displays the
// commission.
Module showCommission()
// Local variables
Declare Real sales, commission
// Constant for the commission rate
Constant Real COMMISSION_RATE = 0.10
// Get the amount of sales.
Display "Enter the amount of sales."
Input sales
// Calculate the commission.
Set commission = sales * COMMISSION_RATE
// Display the commission
Display "The commission is $", commission
End Module
Write the previous While loop using a Do While loop