Tom Kelliher, CS29
Feb. 25, 1997
What we've already discussed:
What we'll discuss today:
The alternatives of two courses of action only one of which is taken depending on the outcome of a condition, which is either true or false.
if (condition)
{
then_body;
}
else
{
else_body;
}
Structure of then_body, else_body:
Example: Printing the amount due on an account. The details:
if (payment is overdue)
{
let $amountDue = $pastDue + $currentBilling + $penalty;
print "You owe: $amountDue";
}
else
{
print "You owe: $currentBilling";
}
Alternative nested if-else structure element: elsif
Example: Convert a numeric grade to a letter grade.
if ($grade < 60)
{
print "F";
}
elsif ($grade < 70)
{
print "D";
}
elsif ($grade < 80)
{
print "C";
}
elsif ($grade < 90)
{
print "B"
}
else
{
print "A"
}
The else is optional.
Example: Print that an account is overdrawn if its balance is less than 0.
if ($balance < 0.0)
{
print "This account is overdrawn.\n";
}
Specifies a block of one or more statements that are repeatedly executed until a condition is satisfied.
while (condition)
{
loop_body;
}
Structure of loop_body? Same as previous bodies.
Example: Sum a set of numbers.
let $sum = 0;
while (there are input numbers to sum)
{
print "Next number: ";
let $number = input from keyboard;
let $sum = $sum + $number;
}
print "The sum is: $sum";
Example: Count from 1 to 10, printing each number.
let $count = 1;
while ($count <= 10)
{
print "$count\n";
let $count = $count + 1;
}
The abstract name for what we are creating is ``algorithm.''
Design a flow chart and pseudo-code to solve each of the following problems: