Pseudocode Reference

Pseudocode is an informal program description that does not contain code syntax or underlying technology considerations. Pseudocode summarizes a program’s steps (or flow) but excludes underlying [implementation] details.  -- techopedia.com

Pseudocode allows you to write easy to read but precise instructions for a program or algorithm. There are many ways to write pseudocode, to reduce uncertainty we will use the following conventions in CSE1321 and CSE 1322.

General Rules

Use upper case for all reserved words. All statements inside loops condition statement are to be indented.

  • CALL
  • CASE … ENDCASE
  • CREATE
  • DO … WHILE … ENDDO
  • FOR … ENDFOR
  • IF  … THEN … ENDIF
  • IF … ENDIF
  • IF … THEN … ELSE … ENDIF
  • METHOD
  • PRINT
  • READ
  • RETURN
  • WHILE … ENDWHILE

Variables

Variables are used to store data. To assign a value to a variable use ←.

Windows/Linux

  1. Check that Num Lock key is pressed to activate the numeric keyboard section.
  2. Hold Alt key and type 27 on number keyboard

Mac

  1. Pull down the Edit menu
  2. Choose Emoji & Symbols or Special Characters
  3. Locate and click on ←

 

letter grade ← A                                stores the value A in the variable letter grade

grade ← 87                                        stores the value 87 in the variable grade

grades [3] ← 100                               stores the value 100 in the third element of the array grades

grade ← grades [3]                            stores the value of the third element of the array grades in the variable grade

grade with bonus ← grade + 10         stores the value grade + 10 in the grade with bonus variable; the value of the variable grade stays the same

Simple Actions

A single line of instructions

  • READ the next grade
  • PRINT 'Hello!'
  • PRINT the average  followed by a newline character
  • CREATE array grades [20][30] 

 Conditions

 Standard conditional statements:

  • IF … ENDIF 
  • IF  … THEN … ENDIF
  • IF … THEN … ELSE … ENDIF
  • CASE … ENDCASE 
     

Important Notes: Any instructions that occur inside a selection must be indented. The statement must show appropriate closing word

 IF … ENDIF     not  IF … ENDCONDITION   not   IF … END

 IF … THEN … ELSE … ENDIF

Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN, ELSE, and ENDIF. The general form is:

 

IF (condition) THEN
       statement block 1
ELSE
       statement block 2
ENDIF

The ELSE keyword and "statement block 2" are optional. If the condition is true, statement block 1 is performed, otherwise statement block 2 is performed.

Example

IF (HoursWorked > NormalMax) THEN
    Display overtime message
ELSE
    Display regular time message
ENDIF

CASE Statement

A CASE construct indicates a multiway branch based on conditions that are mutually exclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used to indicate the various alternatives. The general form is:

 CASE expression OF
      condition 1 : statement block 1 
      condition 2 : statement block 2
      ...
      condition n : statement block n
OTHERS:
      default statement block
ENDCASE

 

The OTHERS clause with its default statement block is optional. Conditions are normally numbers or characters

indicating the value of "expression", but they can be English statements or some other notation that specifies the condition under which the given statement block is to be performed. A certain statement block may be associated with more than one condition.

 

Example

        
  CASE Title OF
       Mr    : PRINT "Mister"
       Mrs   : PRINT "Missus"
       Miss  : PRINT "Miss"
       Ms    : PRINT "Mizz"
       Dr    : PRINT "Doctor"
  ENDCASE
 

Example
 

  CASE grade OF
       A  : points ← 4
       B  : points ← 3
       C  : points ← 2
       D  : points ← 1
       F  : points ← 0
  ENDCASE
 

Loops

Standard looping structures:

  • FOR … ENDFOR


  • FOR EACH 
     
  • WHILE … ENDWHILE
     
  • DO … WHILE … ENDDO 

Important Notes: Any instructions that occur inside an iteration must be indented. The statement must show appropriate closing word

FOR … ENDFOR     not  FOR … ENDLOOP   not   FOR … END

WHILE Loop

The WHILE construct is used to specify a loop with a test at the top. The beginning and ending of the loop are indicated by two keywords WHILE and ENDWHILE. The general form is:

WHILE (condition = true)
       statement block
ENDWHILE

The loop is entered only if the condition is true. The "statement block" is performed for each iteration. At the conclusion of each iteration, the condition is evaluated and the loop continues as long as the condition is true.

Example

WHILE (Population < Limit)
      Population ← Population + Births - Deaths
ENDWHILE

Example

WHILE (employee.type !=  manager AND personCount < numEmployees)
       personCount ← personCount + 1
       CALL employeeList.getPerson with personCount RETURNING employee
ENDWHILE 

REPEAT-UNTIL Statement:

This loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the top. Two keywords, REPEAT and UNTIL are used. The general form is:

   REPEAT
       statement block
  UNTIL condition

 The "statement block" in this type of loop is always performed at least once, because the test is performed after the statement block is executed. At the conclusion of each iteration, the condition is evaluated, and the loop repeats if the condition is false. The loop terminates when the condition becomes true.  

FOR Statement

A FOR statement is good for when you have a definite starting and ending point for your loop.  For example, if you wanted to print out the numbers between 1 to 100, you might write:

FOR i ← 1 to 100
print i
END FOR

There are times when you want to increment the loop counter by something other than one.  This would enable you to "count backwards" or count in increments of, say, 3. There are several ways to accomplish this, but most FOR loops enable you to do it as part of the FOR structure.

FOR i ← 1 to 100 BY 2
print i // Only print out the odd numbers
END FOR

FOR i ← 100 to 0 BY 2
print i // Only print the even numbers from 100 down to 0
END FOR

FOR EACH Statement

This loop is a specialized construct for iterating over a data structure - most often ones that are built into the language.  An example of this could be a "List" of items.   The keywords FOR EACH and END FOR EACH are used. The general form is:

FOR EACH iteration data
    statement block

END FOR EACH

As an example, you may have a List of employees called "employeeList".  To "iterate over it", you might say the following:

FOR EACH employee in employeeList
print employee.name
END FOR EACH

 

In cases where the loop constraints can be obviously inferred it is best to describe the loop using problem domain vocabulary.

Examples

FOR each month of the year (good)
FOR month = 1 to 12 (ok)

FOR each employee in the list (good)
FOR empno = 1 to listsize (ok)


BREAK

Sometimes, like if a certain condition happens, you want the loop to stop and go on to the remaining code.  For simplicity, imagine we want to print numbers 1 through 10, but if we ever see the number 7, that's an emergency and we want the loop to stop processing.  We might have

counter ← 0 
WHILE (counter < 10)
    if (counter == 7) break;
   print counter
  
END WHILE
print ("Outside of loop")

Here the output will be

0
1
2
3
4
5
6
Outside of loop

CONTINUE

A continue is similar in nature to a BREAK, but instead of stopping the loop, it skips over the current iteration and moves on to the next one.  Borrowing from the previous example:

counter ← 0 
WHILE (counter < 10)
    if (counter == 7) continue;    
    print counter
END WHILE
print ("Outside of loop")

Here the output will be

0
1
2
3
4
5
6
8
9
Outside of loop

(Note the missing 7 from above)

NESTED CONSTRUCTS

The constructs can be embedded within each other, and this is made clear by use of indenting. Nested constructs should be clearly indented from their surrounding constructs.

 Example

 total ← zero 
REPEAT
    READ Temperature 
    IF Temperature > Freezing THEN
       total  ← total + 1
    ENDIF
 UNTIL Temperature < zero 
PRINT total

In the above example, the IF construct is nested within the REPEAT construct, and therefore is indented.

CALLING SUBPROCEDURES OR METHODS

Use the CALL keyword. For example:

 CALL AvgAge with StudentAges 
CALL Swap with CurrentItem and TargetItem
CALL Account.debit with CheckAmount
CALL getBalance RETURNING aBalance
CALL SquareRoot with orbitHeight RETURNING nominalOrbit


Examples: 

“Adequate”



FOR X = 1 to 10
    FOR Y = 1 to 10
        IF gameBoard[X][Y] = 0
            Do nothing
        ELSE
            CALL theCall(X, Y) (recursive method)
            increment counter                 
        ENDIF
    ENDFOR
ENDFOR

 

"Better"

moveCount ← 1
FOR each row on the board
    FOR each column on the board
        IF gameBoard position [row][column] is occupied THEN
            CALL findAdjacentTiles with row, column
            INCREMENT moveCount
        ENDIF
    ENDFOR
ENDFOR

(Note: the logic is restructured to omit the "do nothing" clause)

 

"Not So Good"

FOR all the number at the back of the array 
    SET Temp equal the addition of each number
    IF > 9 THEN
        get the remainder of the number divided by 10 to that index
        and carry the "1"
    Decrement one
Do it again for numbers before the decimal
 

"Good Enough (not perfect)" 

Carry ← 0 
FOR each DigitPosition in Number from least significant to most significant
   Total ← FirstNum[DigitPosition] + SecondNum[DigitPosition]
    IF Total > 10 THEN 
       Carry ← 1
       Total ← Total - 10
    ELSE
       Carry ← 0
    ENDIF
    Result[DigitPosition] ← Total
ENDFOR  
IF Carry = 1 THEN 
    RAISE Overflow exception
ENDIF
 

"Pretty Good"

IF robot has no obstacle in front THEN 
       Call Move robot
       Add the move command to the command history
       RETURN true
ELSE
       RETURN false without moving the robot
ENDIF


Example: Write pseudocode to read three positive numbers and printout their average.

METHOD FIND_AVERAGRE
BEGIN
   average ← 0   
   FOR each of three numbers
       READ input_value
   sum ← sum + input_value
   ENDFOR
   average ← sum / 3.0
PRINT average
END FIND_AVERAGRE

Example:  Write pseudocode to read ten numbers and find the maximum value.

METHOD FIND_MAX
BEGIN
   READ input_value
   max ← input_value  //assume first value is the max 
   FOR each of next nine inputted numbers
       READ input_value
   IF max < input_value
      max ← input_value
   ENDIF
   ENDFOR
   PRINT max
END FIND_MAX

Example:  Write pseudocode to read and store grades into an array (assume array size is 30), then print out their total followed by their average.

METHOD GRADES
BEGIN
   // read the grades into the array
   CREATE array grades[30]
   FOR each inputted grade
       READ grade_value
   grades[I] ← grade_value
   ENDFOR
  
   // add up all grades
   total ← 0;
   FOR each element in the array
   total ← total + grades[I]
   ENDFOR
 
   // determine their average
   average ← total / 30.0
   PRINT total
   PRINT average
END GRADES


Passing Parameters/Arguments and RETURN

Sometimes, we'd like to be able to "send" information to a method, and we'd like to get a result back.  This involves four things:

1) Passing data "called arguments" or "actual parameters" to a method

2) Having a place in that method for that data to land (or be stored) - which are called "formal parameters"

3) Inside the method, returning a result back to whoever called it

4) Having a variable to "catch" the result from the place the method was called

Realize that it's not necessary to use parameters, and it's not necessary to have a return type; it depends on the situation. 

For example, we may want to have a method that does a simple task, like add two numbers together and then RETURN the result.  This would involve passing parameters to a method, and accepting whatever value it returns.

To define the method, we can say:

METHOD addTwoNumbers (parameters: num1, num2)
BEGIN
     result ← num1 + num2
     RETURN result
END addTwoNumbers

However, this method won't run until it's called.  It must be passed the exactly correct set of parameters!  In this case, addTwoNumbers() wants to numbers.  It doesn't want one number.  It doesn't want a number and character.  It will only accept two numbers.  As such, that's how we'll call it, and we'll "catch" whatever information it sends back to us.

CREATE w, x, y, z, temp
w ← 5
x ← 7
y ← -3
z ← 10
temp ← addTwoNumbers(w, x)  // w gets copied into num1, x gets copied into num2
print (temp)  // the number 12 prints to the screen
temp ← addTwoNumbers (y, z)  // y gets copied into num1, z gets copied into num2
print (temp)  // the number 7 prints on the screen

This is the benefit of parameters!  The variables num1 and num2 above "catch" the incoming data each time we call it - and you can see that what we pass can change each time we call it as well.

The first time we call addTwoNumbers, we pass it w and x.  So, a 5 gets copied into num1 and a 7 gets copied into num2.  The method then adds those two numbers and puts it into result.  Then, the method RETURNs result, which goes into the variable temp.  In the second call, a -3 gets copied into num1 and a 10 goes into num2.  The method adds them together and returns a 7, which goes into temp again.

©