Elements of Pseudo Code

Tom Kelliher, CS29

Feb. 25, 1997

What we've already discussed:

What we'll discuss today:

Conditional Execution

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:

  1. There is a condition: payment might be overdue.

  2. If payment is overdue, the amount due is the past due amount plus the current billing amount plus a penalty.

  3. If payment has been received, the amount due is just the current billing.

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";
}

Repetitive Execution

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;
}

Problems to Work on in Groups

The abstract name for what we are creating is ``algorithm.''

Design a flow chart and pseudo-code to solve each of the following problems:

  1. Determine which of two numbers is larger, and print the larger number.
  2. Read numbers from a keyboard until a zero is input, then you are finished.
  3. Read positive numbers from the keyboard until the user enters a zero value, then print the largest number read.
  4. Print the factors of an integer which is input from the keyboard.
  5. Print the factors of numerous integers which are input from the keyboard. The user inputs integers one at a time. After each integer is input, you are to output the factors. If the input is zero, you are finished.


Thomas P. Kelliher
Sat Feb 22 20:09:02 EST 1997
Tom Kelliher