Pseudocode

An algorithm is the steps that a programmer will write that will become a program. It is written in a form of structured language called Pseudocode.

Once an algorithm is created using pseudocode, it is simple to translate it into real programming code. It gives an opportunity to detect any logic errors prior to actual coding, which is a lot more expensive and time consuming. It is used for planning the programming.

What is pseudocode?

Pseudocode consists of short, English phrases used to explain specific task within a program’s algorithm. Pseudocode should not include keywords in any specific computer languages. It should be written as a list of consecutive phrases. You should not use flowcharting symbols but you can draw arrows to show looping processes. Indentation can be used to show the logic in pseudocode as well. For example, a first-year, 9th grade Visual Basic programmer should be able to read and understand the pseudocode written by a 12th grade AP Data Structures student. In fact, the VB programmer could take the other students pseudocode and generate a VB program based on that pseudocode.

Why is pseudocode necessary?

The programming process is a complicated one. You must first understand the program specifications, of course. Then you need to organise your thoughts and create the program. This is a difficult task when the program is not trivial (i.e. easy). You must break the main tasks that must be accomplished into smaller ones in order to be able to eventually write fully developed code. Writing pseudocode WILL save you time later during the construction & testing phase of a program’s development.

How to Write Pseudocode

Keep in mind that, if you have used pseudocode to write your algorithm, the coding will become very simple.

The Six Basic Computer Operations

Basic Computer Operation Description Examples
A computer can receive (input) information Received information is called input. READ and Get usually used mean to receive input. READ means that the information comes from a file. GET means that the information will come from a user entering it. You would not specify from which file you will be receivign the information just that you will get it from one.
  • Read student name (from the student file)
  • Get system date (from the computer system).
  • Read student ID number
  • Get order.
A computer can put out (ouput) information Information created by your program is called output. The verb PRINT means that the information will be sent to a printer. The verb WRITE means that the information will be sent to a file. The verbs, PUT, OUTPUT, and DISPLAY can all be used to say that the information will be displayed on the monitor.
  • Print "End of the Output"
  • Write student record to master file
  • Put out name, address and post code
  • Output grade; Display "an input error occurred, please re-enter"
A computer can perform arthmetic

A computer can perform arithmetic operation. A programmer may use actual mathematical symbols or the words for those symbols. The verbs COMPUTE and CALCULATE can be used to show assignment in pseudocode.

There is a mnemonic called PEMDAS. The letters form a syaing that is "Please Excuse My Dear Aunt Sally". They help you to remember the mathematical order of operations. The P is parenthesis; anything in parenthesis is done first. The E is exponents and they are done next. The M is multiply and the D is divide. These are calculated, from left to right next. The A is addition and the S, subtraction and are done last, from left to right order.

  • Divide total_score by student_count
  • class_average = total_score / student_count
  • Compute C = (F – 32) * 5 / 9
  • Calculate the number of registrations
  • The + symbol means to add: 2 + 3 = 5.
  • The – symbol means to subtract: 2 – 3 = -1.
  • The * symbol means to multiply: 2 * 3 = 6.
  • The / symbol means to divide: 2 / 3 = .66667
  • The ^ symbol means to the power of. 2 ^ 3 = 8.
A computer can assign a variable or memory location
  1. There are three cases where you may write pseudocode to assign a value to a variable or memory locations
  2. To give data an initial value. The verb Initialize or Set are used.
  3. To assign a value as a result of some processing, the symbol "=" is used

To keep a piece of information for later use, the verbs SAVE or STORE are used. The first time that you create a variable, you reserve space in your computer’s memory (RAM) for that variable. The first time that you give that variable a value, you can initialized it. MyNumber = 5 assignes the value of 5 to the variable called MyNumber. The verb used in pseudocode to initialize a value is INITIALISE or SET. The equal operator (=) is used to do assignment. I can set MyNumber to have the initial value of 5 and then later in the program write MyNumber = 10, which would effectively give a new value to the variable. MyNumber would then not have the value of 5; it would have the value of 10.

  • Initialize total_score to 0: total_score = 0
  • Set student_count to 0: student_count = 0
  • total_score = total_score + score 1
  • student_count = student_count + 1
  • class_average = total_score / student_count
  • store class_average in class_average_quiz1
A computer can compare two variables and select one of the two alternative choices.

This is the control structure selection, more commonly known as an IF/THEN/ELSE statement. IF, THEN, ELSE and ENDIF are the words used to do this. The comparison of data is establised in the If clause, and the choice of alternatives is determined by the Then or Else options. Only one of these alternatives will be performed.

The example reads as follows; if the student is part-time student, then "add 1 to part_time_count" is performed. Otherwise, the computer skips to the Else clause to perform "add 1 to full_time_count" instruction.

If student is part_time Then

add 1 to part_time_count

Else

add 1 to full_time_count

EndIf

A comptuer can repeat a set of actions

This means that it is possible to have my program repeat a set of instructions over and over or some specified amount of times. That is the control structure interation, more commonly known as a loop. DOWHILE and ENDO are the words used in pseudocode. The controlling conditionis something that is true when the loop starts and then is changed during the program’s running to become false. ENDO, the delimiter, helps the programmer see the end of the loop. The DOWHILE and ENDO words are lined up with each other and the body of the loop is indented. When you actually write this code, the comiler will ignore the indention, but it makes the code easier to read.

In the example shown in the column to the right, the set of instruction in the Do While loop will be performed repeatedly as long as student_total is less than 30. And each time computer goes through the loop, the value of student_total will be incremented by 1, in which eventually will make the student_total to be equal to 30, and terminate the loop.

Do While student_total <30

Read student record
Print student name, address
Add 1 to student_total

EndDo

Rules for Pseudo

It has been outlined that doing pseudo-code before you code reveals many probelms early and allows for clear thinking. Using pseudo-code is one the quickest way to communicate your ideas across to other developers. To that end this document to gives the necessary information for other developers to read and write in Pseudocode that can be converted by GPC. It based upon experience and further refinement to create an object-oriented pseudocode language that is independent of any one language. Below are rules to follow when writting strict pseudocode.

  1. The only basic types of boolean, character, string, integer, and real.
  2. Types can be expanded that are specific to a project. For example if you have a program "A" that has a class called foo in the pseudocode for a class called bar you can instantiate foo.
  3. To ease develoment for general comiling all pseudocode files end with the extensions pc, so that they are ignored by the GCC complier
  4. Everything should be done "faily high". I know it’s imprecise but your implementation should be detailed enough for any programmer to grasp an understanding on how your code works.
  5. You should comment the pseudocode just like normal code.
  6. Language calls to the target language from within the pseudocode is allowed.
  7. Descriptive functions are allowed in the pseudocode. For an example, clearScreen()
  8. Statements are evaluated from right to left, top to bottom, with each new statement on a new line.
  9. As a general rule, you want to keep each class in its own pseudocode file for added clarity.
  10. A variable name can consist of any combinations of letters, numbers, and the underscore (_). However, the first character is a variable must be a ltter.
  11. The language is case-sensitive.

Keywords Used

Below is a table which shows line-by-line listings of the features and rules of the pseudocode language.

Programming Structure Pseudo-Keyword / Examples Description
Comments { brackets comment }
# single line comment
As with any good code, your files should be commented as well. Comments are of course not executed like normal languages. Multiline comments are surrounded by braces {}. Single line comments use the hash mark #. Comments should be written assuming that they will carry over into the code. Comments for variables passed in a function are required and indicated by a colon :. For an example: 
Maths addition (+), subtraction (-),
multiplication (*), division (/),
modulus (%), the exponent (^),
less than (<), equal (=),
greater than (>),
less than or equal to (<=),
and greater than or equal to (>=), increment (inc), decrement (dec)
These are the following known math operators, note for both the inc and dec operators if a value isn’t provided in front of them, 1 is assumed
Assignment Operators variable := expression

The assignment operator looks like the following :=. Note that it is not the same as =, which is a test for equivalence. An assignment operator will take the value from the right side and replace the value of the left side with it. The variable "n" now contains the value 5

Literals This is a character: ‘a’ 
This is a string: “foobar”
There are two type of literals: a string literal and a character literal. A character literal is used by placing single quotes around the character. A string literal is used by placing double quotes around the text.
Block Statements begin 
    statement1 
    statement2 
    statement3 
    … 
    statmentN 
end
Statements are all blocked off with the keywords begin and end. Each statement in the block is executed sequentially. Statements inside these blocks should carry the same indentation to ease reading
Grouping b := (a / 2) + 6, a := 1 

You can group expressions using parentheses (). As in maths, parentheses have the highest order of precedence. Another form of group can be achieved using the comma (,). This will extend a statement by one.

This assigns “a” the value of 1, divides “a” by 2, adds six, and assigns the resulting value into “b”.

Variables declare integer i 
declare constant integer j := 12 
declare permanent integer j 
enumeration Days 
begin 
    Monday, 
    Tuesday, 
    Wednesday, 
    Thursday, 
    Friday, 
    Saturday, 
    Sunday 
end 
declare Days today
Variables must always be declared before they are used. Variables are only known within their block statement scope. To create a variable use the keyword declare before the variable type. After the variable type follow with the variables name. A variable can be made constant by using the keyword constant. Constants must be assigned a value at the time of their declaration. A global variable can be made to exist only within the scope of the file by using the keyword permanent. This has the same usage and meaning as found in C++. You can create a user defined type by using the keyword enumeration followed by the type name. After the type name give an integer list of values. All enumerations start at zero and follow sequentially, unless otherwise specified using an assignment operator
Input/Output string message 
read message 
print “You wrote ” + message 
printError “Something horrible has happened.”
Input from a user is easily done using the keyword read then followed by the variable you want the input to be filled with. This keyword indicates that you will read the input for the user from the standard input. Output for a user to read from the standard output is indicated by the keyword print or printLine followed by what you want to have displayed to the user. The only difference between print and printLine is explained below. If there is an error that you would like to have printed to the standard error use the keyword printError. For the keywords printLine andprintError adds a newline at the end of the statement. 
Conditional Construction If, Then, Else, ElseIf (elif), Case, Select, Default, Break

The basic if-construct support is: if condition then statement else statement. You can extend the if statement by using the elif keyword, which acts as an else-if construct statement. 

If you need to test just one variable for several conditions, then a case statement would be more appropriate. There are three keywords involved in a case statement: caseselect, and default. The keyword case is followed by the variable you want to test. Blocking that off you precede each test using the keyword select. To handle a default case selection use the keyword default. A specific series of select statements are executed until the next select statement is declared, or the keyboard break is encountered.

Loop Constructions For, Loop, To, Stepping, Break, Continue,While, Iterate, As, Until, Do

The purpose of a loop is to execute the same sequence of statements given certain conditions. If you want to completely exit prematurely from any loop construct use the keyword break. Break will exit out of the first loop construct that it encounters. If you want to go on to the next iteration in the loop construct use the keyword continue. Continue will stop the loop execution and restart the loop construct at the next iteration. The for loop is fairly straight forward as its use is based on numerical iterations. There is a looping variable with an inclusive starting point and an ending point that is exclusive. The for loop will execute a single statement, which follows the final value on a new line. The for loop can of course be made to execute more statements by using block statements. The looping variable follows the keyword for. After the looping variable is the keyword loops followed by the starting value of the loop. The final value follows the keyword to which follows the initial value. During execution, the for loop will test to be sure the looping variable is within the specified range, and if so will execute the statement. After executing the statement, the for loop will increment the looping variable by one (the default) and re-test to see if the looping variable is still within range. If you do not want to increment by one you can use the stepping keyword to change how the for loop increments.

The keyword while precedes any conditional expression. The statement that the while loop should execute follows on a new line. The while loop can be made to execute more lines of code by using block statements. The while loop only executes only if the condition supplied evaluates to true. After executing the statement, it retests the condition. 

The keyword iterate precedes the iteratable object. Following the object to iterate, is the variable name to use for each iterated object during the statement, which is preceeded by the keyword as. The iterator variable can be treated as if you were working on the actual value that the iterator object contains. The ending conditional expression is preceeded by the keyword until. The statement that the iteratable for-loop should execute follows on a new line. The iteratable for-loop can be made to execute more lines of code by using block statements. The iteratable for-loop only executes only if the condition supplied evaluates to true. After executing the statement, it retests the condition.

Arrays Array, [ ] Operators, Pointers, Value, Address, Destory

To declare that a variable is an array structure use the keyword array after the type of the variable. After the declaration you can access any element in the array structure using square brackets to index an array. You can specify how many elements the array should initially have by wrapping the number desired in parentheses following the variable name. As far as type safety and method calls you can treat the array storage in the pseudocode similar to vectors in C++ or like the targeted language. If the targeted language is used, conversion support may be limited. Individual indices are accessed using the [] operators. Range checking is conversion specific.

In addition more advance features such as pointers are available to use, though not all languages support it. The keyword pointer is used when declaring the variable. The keyword value is used after a variable to retrieve the value of the memory address of the pointer. The keyword address is used to retrieve the memory address of a variable. The keyword destroy will free the memory address pointed to by the variable.

Function Function, Procedure, Begin, End, noResult, virtual, thread, abstract, launch, constructor, destructor, startHere A function is a statement that can be called to execute a specific sequence of statements. To call a function write the function’s name followed by parentheses, passing any necessary arguments inside the parentheses. If the function being called takes more than one argument separate each argument by a comma. 
Some function you write may need a return type. Return types are declared by listing the return type following the keyword procedure. If your function does not have a return value, then use the keyword noResult. To return a specific value or expression use the keyword result inside the function, placing result before the value or expression you wish to return. The statements for the function will follow on a new line.
The statements of a function must be enclosed by block statements. An argument list can be provided after the function’s name inside of the parentheses. The description will follow after the variable name preceded by a colon. This should aid in the documentation later on. The arguments type will preceded the arguments name. Each variable in the procedure list is separated by a comma. 
A function has scope. It can be either global or only within a class. A global function is created by not having the function inside a block statement. When a procedure is inside of a class it may have additional properties listed before the procedure keyword. These keywords are virtualthread and abstract. I am sure you are familiar with virtual and abstract and will not waste time explaining them. The thread keyword is used to indicate that this function is to be threaded in the implemented language. The actually starting of a threaded function is done with the keyword launch
There are three kinds of special function constructordestructor, and startHere. The keyword procedure is not needed in these specific cases. Constructors and destructors both hold the same meaning as they would in C++. The startHere special procedure is where execution would begin in a programme.
Classes and Aggregate Data Types class, inherits, public, protected, private, attribute, addin, base, in, scope, scopeEnd

All classes can be created using the keyword class. A class can be made up of other known classes using the keyword inherits after the name of the subclass. Procedures listed in the class can be given three kinds of scope publicprotected, and private. These scopes carry the same meaning as in C++. If no scope is listed anywhere in the class everything is assumed to be public, else the last declared scope is used. Scopes do not need blocks, but they do need to be on their own line.

The keyword attribute is used to declare class member variables. When declaring a class member variable the keyword declare is not necessary as it is implied with attribute. As always you can use blocks to extend the statements. If a constructor and/or a destructor is not explicitly declared they will be created. For how to signify a constructor and a destructor see the information given in the procedures section.

If a file is going to be needed when the pseudocode is converted and compiled into the specified language, then the keyword addin is used before the name of the file to indicate the inclusion of that file into the code. When you need to call the method of a base class use the keyword base before the method’s name. The only exception is when you are calling the base class’s constructor, in that case you only need to use the keyword base

If you need to specify the scope of something you may use the keyword in, proceeded by the name of the variable you’re interested in and followed by the location of that variable. A class must be enclosed with a unique name using the keywords scope and scopeEnd. The keyword scope is similar to the #include and the #ifndef in C++ combined. The keyword scopeEnd is similar to #endif in C++.

Error Handling error, handle, attempt, print, exit Error handling keywords are: attempterrorhandle. The keyword attempt marks to watch for possible thrown errors. The keyword error will throw a specified error. The error may be as simple as a string. The keyword handle provides a check to catch a specific error and handle it. If an error is not handled as it propagates up and reaches the start of the programme, the programme will print the contents of the error and exit.