Pseudo code Standard

Data structures & algorithms topics
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Pseudo code Standard

Post by Neo » Wed Mar 17, 2010 10:11 pm

Pseudo code is a kind of structured English for describing algorithms. It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax. At the same time, the pseudo code needs to be complete. It describe the entire logic of the algorithm so that implementation becomes a rote mechanical task of translating line by line into source code.

In general the vocabulary used in the pseudo code should be the vocabulary of the problem domain, not of the implementation domain. The pseudo code is a narrative for someone who knows the requirements (problem domain) and is trying to learn how the solution is organized. E.g.,

Code: Select all

Extract the next word from the line (good) 
set word to get next token (poor) 

Append the file extension to the name (good) 
name = name + extension (poor) 

FOR all the characters in the name (good) 
FOR character = first to last (ok)
Note that the logic must be decomposed to the level of a single loop or decision. Thus "Search the list and find the customer with highest balance" is too vague because it takes a loop AND a nested decision to implement it. It's okay to use "Find" or "Lookup" if there's a predefined function for it such as String.indexOf().

Each textbook and each individual designer may have their own personal style of pseudo code. Pseudo code is not a rigorous notation, since it is read by other people, not by the computer. There is no universal "standard" for the industry, but for instructional purposes it is helpful if we all follow a similar style. The format below is recommended for expressing your solutions in our class.

The "structured" part of pseudo code is a notation for representing six specific structured programming constructs: SEQUENCE, WHILE, IF-THEN-ELSE, REPEAT-UNTIL, FOR, and CASE. Each of these constructs can be embedded inside any other construct. These constructs represent the logic, or flow of control in an algorithm.

It has been proven that three basic constructs for flow of control are sufficient to implement any "proper" algorithm.
  • SEQUENCE is a linear progression where one task is performed sequentially after another.
  • WHILE is a loop (repetition) with a simple conditional test at its beginning.
  • IF-THEN-ELSE is a decision (selection) in which a choice is made between two alternative courses of action.
Although these constructs are sufficient, it is often useful to include three more constructs:
  • REPEAT-UNTIL is a loop with a simple conditional test at the bottom.
  • CASE is a multiway branch (decision) based on the value of an expression. CASE is a generalization of IF-THEN-ELSE.
  • FOR is a "counting" loop.
SEQUENCE
Sequential control is indicated by writing one action after another, each action on a line by itself, and all actions aligned with the same indent. The actions are performed in the sequence (top to bottom) that they are written.

Example (non-computer)
  1. Brush teeth
  2. Wash face
  3. Comb hair
  4. Smile in mirror
Example
  1. READ height of rectangle
  2. READ width of rectangle
  3. COMPUTE area as height times width
Common Action Keywords
Several keywords are often used to indicate common input, output, and processing operations.
  • Input: READ, OBTAIN, GET
  • Output: PRINT, DISPLAY, SHOW
  • Compute: COMPUTE, CALCULATE, DETERMINE
  • Initialize: SET, INIT
  • Add one: INCREMENT, BUMP
IF-THEN-ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN, ELSE, and ENDIF. The general form is:

Code: Select all

IF condition THEN 
       sequence 1
ELSE 
       sequence 2
ENDIF
The ELSE keyword and "sequence 2" are optional. If the condition is true, sequence 1 is performed, otherwise sequence 2 is performed.

Example

Code: Select all

IF HoursWorked > NormalMax THEN 
       Display overtime message
ELSE 
       Display regular time message
ENDIF
WHILE
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:

Code: Select all

WHILE condition 
       sequence
ENDWHILE
The loop is entered only if the condition is true. The "sequence" 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

Code: Select all

WHILE Population < Limit 
       Compute Population as Population + Births - Deaths
ENDWHILE
Example

Code: Select all

WHILE employee.type NOT EQUAL manager AND personCount < numEmployees 
       INCREMENT personCount
       CALL employeeList.getPerson with personCount RETURNING employee
ENDWHILE
CASE
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:

Code: Select all

CASE expression OF 
       condition 1 : sequence 1 
       condition 2 : sequence 2 
       ... 
       condition n : sequence n 
       OTHERS: 
       default sequence
ENDCASE
The OTHERS clause with its default sequence 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 sequence is to be performed. A certain sequence may be associated with more than one condition.

Example

Code: Select all

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

Code: Select all

        CASE  grade  OF
                A       : points = 4
                B       : points = 3
                C       : points = 2
                D       : points = 1
                F       : points = 0
        ENDCASE
REPEAT-UNTIL
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:

Code: Select all

REPEAT 
       sequence
UNTIL condition
The "sequence" in this type of loop is always performed at least once, because the test is peformed after the sequence 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
This loop is a specialized construct for iterating a specific number of times, often called a "counting" loop. Two keywords, FOR and ENDFOR are used. The general form is:

Code: Select all

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

Example

Code: Select all

       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)
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

Code: Select all

SET total to zero 
REPEAT 
       READ Temperature 
       IF Temperature > Freezing THEN 
              INCREMENT total 
       END IF
UNTIL Temperature < zero 
Print total
In the above example, the IF construct is nested within the REPEAT construct, and therefore is indented.

INVOKING SUBPROCEDURES
Use the CALL keyword. For example:

Code: Select all

       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
EXCEPTION HANDLING

Code: Select all

       BEGIN 
              statements 
       EXCEPTION 
              WHEN exception type 
                     statements to handle exception
              WHEN another exception type 
                     statements to handle exception
       END 

Sample Pseudocode
"Adequate"

Code: Select all

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                  
        END IF
    END FOR
END FOR
"Better"

Code: Select all

Set moveCount to 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 
        END IF 
    END FOR
END FOR
(Note: the logic is restructured to omit the "do nothing" clause)

"Not So Good"

Code: Select all

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)"

Code: Select all

SET Carry to 0 
FOR each DigitPosition in Number from least significant to most significant 

    COMPUTE Total as sum of FirstNum[DigitPosition] and SecondNum[DigitPosition] and Carry  

    IF Total > 10 THEN 
        SET Carry to 1 
        SUBTRACT 10 from Total 
    ELSE 
        SET Carry to 0 
    END IF 

    STORE Total in Result[DigitPosition] 

END LOOP  

IF Carry = 1 THEN 
    RAISE Overflow exception 
END IF 

"Pretty Good" This example shows how pseudocode is written as comments in the source file. Note that the double slashes are indented.

Code: Select all

public boolean moveRobot (Robot aRobot) 
{ 
    //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 
    //END IF 
} 
Example Java Implementation
source code statements are interleaved with pseudocode.
comments that correspond exactly to source code are removed during coding.

Code: Select all

public boolean moveRobot (Robot aRobot) 
{ 
    //IF robot has no obstacle in front THEN 
    if (aRobot.isFrontClear()) 
    { 
        // Call Move robot 
        aRobot.move(); 
        // Add the move command to the command history 
        cmdHistory.add(RobotAction.MOVE); 
        return true; 
    } 
    else // don't move the robot 
    { 
        return false; 
    }//END IF 
}
User avatar
Face
Major
Major
Posts: 727
Joined: Thu Feb 18, 2010 5:06 pm
Location: SRI LANKA.KANDY.

Re: Pseudo code Standard

Post by Face » Thu Mar 18, 2010 12:48 pm

THANK YOU!

really good.
i got really good clear idea from your lesson..
now i got the basics.
i think now i can refer those notes & some learning sites.

if you don't mind please give me good site to study pseudo cords.
stranded site for my studies..
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Pseudo code Standard

Post by Neo » Thu Mar 18, 2010 2:14 pm

I really don't know a good site for Pseudo Code (not cord). most of the articles that I have seen including the one at wikipedia are bit primitive. Google further to find a matching one.
leesandy44
Corporal
Corporal
Posts: 10
Joined: Sat Mar 20, 2010 8:45 am

Re: Pseudo code Standard

Post by leesandy44 » Sun Mar 21, 2010 9:39 am

Can anyone send me some exercises to practice pseudo codes??? or at least a site to get some exercises...
User avatar
Face
Major
Major
Posts: 727
Joined: Thu Feb 18, 2010 5:06 pm
Location: SRI LANKA.KANDY.

Re: Pseudo code Standard

Post by Face » Sun Mar 21, 2010 10:03 am

use these links to study pseudo code systems..

http://en.wikipedia.org/wiki/Pseudocode

http://userpages.wittenberg.edu/bshelbu ... rithms.htm

http://en.wikibooks.org/wiki/LaTeX/Algo ... Pseudocode

http://cnx.org/content/m18649/latest/

http://www.experiencefestival.com/pseud ... pseudocode

these sites are not recommended for for studies.
but try some.it is really hard to find basic in pseudo code systems.
this algorithm contacted with programming soo it is when you learn basics difficult to deel with programming languages+pseudo codes..

try wiki questions in Wikipedia.
User avatar
Face
Major
Major
Posts: 727
Joined: Thu Feb 18, 2010 5:06 pm
Location: SRI LANKA.KANDY.

Re: Pseudo code Standard

Post by Face » Sun Mar 21, 2010 10:14 am

I found some questions but with out answers.

http://mias.uwimona.edu.jm/training/cit ... nt%201.pdf



Q1).A professor allows students to drop the 2 lowest scores on the 10 quizzes given during the semester. Each quiz is worth a max of 100 points.
Design an application that allows the professor to enter a student name and 10 quiz scores for each of her 20 students. The output lists each students name,total points for each students 8 highest scoring quizzes...needs to call its sort module in the logic and assume that the module sorts in ascending order.?

Answerer -
Create a variable named names to hold 20 names.
Create a variable named scores to hold 10 scores for 20 students.
For each student:
- Output a message to ask for input of the name.
- Get the input for the name and set it to names in the appropriate spot/index.
- For each score:
- - Ouput a message to ask for input of the score.
- - Get the input for the score and set it to scores in the appropriate spot/index.
- End for.
End for.

Sort the scores for each student. // This is the call to the sort module. I don't know if you have to write psuedo code for this or not, but I will leave that for you to do if you do need to do it.

For each student.
- Output the name.
- Create a variable to hold the sum of the scores, set this variable to 0.
- For each score starting at score number 3.
- - Add the score to the variable holding the sum of the scores.
- End for
- Output the sum of the scores.
End for.
leesandy44
Corporal
Corporal
Posts: 10
Joined: Sat Mar 20, 2010 8:45 am

Re: Pseudo code Standard

Post by leesandy44 » Sun Mar 21, 2010 10:27 am

thank you..
I'll check the links...
leesandy44
Corporal
Corporal
Posts: 10
Joined: Sat Mar 20, 2010 8:45 am

Re: Pseudo code Standard

Post by leesandy44 » Wed Mar 24, 2010 9:59 am

Can anyone solve this for me?

The Hailstone Series is generated using the following high level algorithm:
1. Pick a positive number ( 0 or greater )
2. If it is odd, triple the number and add one
3. If it is even, divide the number by two.
4. Go back to step 2.

This series will eventually reach the repeating "ground" state:
4; 2; 1; 4; 2; 1

Here is the sequence generated for an initial value of 26:
26; 13; 40; 20; 10; 5; 16; 8; 4; 2; 1; 4; 2; 1

Problem
Convert the high-level algorithm above into pseudo-code. Also, the following values should be displayed during execution
of your algorithm.
How many items are in the sequence ?
What is the largest number computed in the sequence ?

Requirements
1. You can assume the "ground" state commences when the integer 4 is computed. At this stage you can terminate
computation of the series.
2. If 0 is input as the positive number your algorithm should terminate without calculating the series.
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Pseudo code Standard

Post by Neo » Wed Mar 24, 2010 12:59 pm

No one is able to do your home work ;) . So just write something by your own and post here so we can see whether it is correct, add mods, etc...
User avatar
Face
Major
Major
Posts: 727
Joined: Thu Feb 18, 2010 5:06 pm
Location: SRI LANKA.KANDY.

Re: Pseudo code Standard

Post by Face » Wed Mar 24, 2010 1:14 pm

Neo that's is not home work buddy...
I post some questions from some sites.leesandy44 got hard to answer them.but the problem is there are no answers in those site..I could only found the questions with out answers..

soo buddy....please suggest a proper answer to that.
Post Reply

Return to “Data Structures & Algorithms”