You are on page 1of 11

Pseudocode, Algorithm and Flowchart

Computer Programming I

An algorithm is a procedure for solving a problem in terms of the actions to be executed and the order in which those actions are to be executed. An algorithm is merely the sequence of steps taken to solve a problem. The steps are normally "sequence," "selection, " "iteration," and a case-type statement. In C, "sequence statements" are imperatives. The "selection" is the "if then else" statement, and the iteration is satisfied by a number of statements, such as the "while," " do," and the "for," while the case-type statement is satisfied by the "switch" statement. Pseudocode is an artificial and informal language that helps programmers to develop algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool. The rules of Pseudocode are reasonably straightforward. All statements showing "dependency" are to be indented. These include while, do, for, if, switch. Examples below will illustrate this notion. GUIDE TO PSEUDOCODE LEVEL OF DETAIL: Given record/file descriptions, pseudocode should be created in sufficient detail so as to directly support the programming effort. The purpose of pseudocode is to elaborate on the algorithmic detail and not just cite an abstraction. There is not fixed rule for writing the PseudoCode. It differers from one company to another, however there is certain basic Pseudocode standard as follows: 1. Write only one statement per line. 2. Capitalize keyword used for Pseudocode, like READ, PRINT etc 3. Start all the sequences from same column in case of without use of selection(i.e. body of if, for , while etc) 4. Make Pseudocode as Programming language independent. 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 How To WRITE PseudoCode? 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

Prepared by Om Prakash Mahato

Pseudocode, Algorithm and Flowchart


Computer Programming I

A computer can perform arithmetic operation.


A programmer may use actual mathematical symbols or the words for those symbols. For example: "Add score to total_score" is same as "total_score = total_score + score" (programming languages use mathematical equations to assign values to memory locations. In this case, a new value of total_score is assigned to a memory location named total_score by adding score to the current (not new) value of total_score)

The following symbols can be used in pseudocode: + for Add, - for Subtract, * for Multiply, / for Divide, ( ) for Parentheses For more example: o Divide total_score by student_count o class_average = total_score / student_count o Compute C = (F - 32) * 5 / 9 When writing mathematical calculation for the computer, the order of operation should be considered; otherwise you may end up with incorrect values. The order of operators are following: 1. ( ) : Values within parentheses are always evaluated first. 2. ^ : Exponentiation (raising a number to a power) is second. 3. - : Negation (creating a negative number) is third. 4. * and / : Multiplication or division is fourth. 5. \ : Integer division (a.k.a. Div) is fifth. 6. Mod : Remainder division is sixth. 7. + or - : Addition and subtraction are last. Example: For an expression Total = 10 + 15 * 2 / 4 ^ 2 -(2 + 3) , the order of computation is following: 0. Total = 10 + 15 * 2 / 4 ^ 2 -(2 + 3) 1. Total = 10 + 15 * 2 / 4 ^ 2 -(5) 2. Total = 10 + 15 * 2 / 16 -(5) ( 5 as a negative value) 3. Total = 10 + 15 * 2 / 16 - 5 4. Total = 10 + 30 / 16 - 5 5. Total = 10 + 1.875 - 5 6. Total = 11.875 - 5 7. Total = 6.875

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.
Prepared by Om Prakash Mahato 2

Pseudocode, Algorithm and Flowchart


Computer Programming I

Example CODE: SELECT ALL IF HoursWorked > NormalMax THEN Display overtime message ELSE Display regular time message ENDIF The Repetition structure can be implemented using Repeat Until Loop The While Loop The For Loop

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:
Prepared by Om Prakash Mahato 3

Pseudocode, Algorithm and Flowchart


Computer Programming I

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
Prepared by Om Prakash Mahato 4

Pseudocode, Algorithm and Flowchart


Computer Programming I

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.

Prepared by Om Prakash Mahato

Pseudocode, Algorithm and Flowchart


Computer Programming I

EXAMPLES of PseudoCode Example 3: This is the pseudo-code required to input three numbers from the keyboard and output the result. Use variables: sum, number1, number2, number3 of type integer Accept number1, number2, number3 Sum = number1 + number2 + number3 Print sum End program Example 4: The following pseudo-code describes an algorithm which will accept two numbers from the keyboard and calculate the sum and product displaying the answer on the monitor screen. Use variables sum, product, number1, number2 of type real display Input two numbers accept number1, number2 sum = number1 + number2 print The sum is , sum product = number1 * number2 print The Product is , product end program Note: -The logical operators used in our pseudo-code are = is equal to > is greater than < is less than >= is greater than or equal <= is less than or equal <> is not eaqual to LOGICAL OPERATORS: AND, OR, NOT AND: if any of the conditions are false, the whole expression is false. ex: IF day = Saturday AND weather = sunny WRITE Lets go to the beach! ENDIF OR: if any of the conditions are true, the whole expression is true ex: IF month = June OR month = July OR month = August WRITE Yahoo! Summer vacation! ENDIF NOT: reverses the outcome of the expression; true becomes false, false becomes true. ex: IF day <> Saturday AND day <> Sunday WRITE Yuk, another work day ENDIF Example 5: The following shows how the selection control structure is used in a program where a user chooses the options for multiplying the numbers or adding them or subtracting. Use variables: choice, of the type character ans, number1, number2, of type integer display choose one of the following display m for multiply display a for add
Prepared by Om Prakash Mahato 6

Pseudocode, Algorithm and Flowchart


Computer Programming I

display s for subtract accept choice display input two numbers you want to use accept number1, number2 if choice = m then ans = number1 * number2 if choice = a then ans = number1 + number2 if choice = s then ans = number1 - number2 display ans Example 6: The program is to input a examination mark and test it for the award of a grade. The mark is a whole number between 1 and 100. Grades are awarded according to the following criteria: >= 80 Distinction >= 60 Merit >= 40 Pass < 40 fail The pseudo-code is Use variables: mark of type integer If mark >= 80 display distinction If mark >= 60 and mark < 80 display merit If mark >= 40 and mark < 60 display pass If mark < 40 display fail Example 8: The following program segment outputs a message to the monitor screen describing the insurance available according to a category input by the user. Use variables: category of type character Display input category Accept category If category = U Display insurance is not available Else If category = A then Display insurance is double Else If category = B then Display insurance is normal Else If category = M then Display insurance is medically dependent Else Display entry invalid This can be expressed in a case statement as follows: Use variables: category of type character Display input category Accept category DO case of category CASE category = U Display insurance not available CASE category = A Display insurance is double CASE category = B
Prepared by Om Prakash Mahato 7

Pseudocode, Algorithm and Flowchart


Computer Programming I

Display insurance is normal CASE category = M Display insurance is medically dependent OTHERWISE: Display entry is invalid ENDCASE Instead of using the word otherwise, one can use else. Example 10. A survey has been carried out to discover the most popular sport. The results will be typed into the computer for analysis. Write a program to accomplish this. REPEAT DISPLAY Type in the letter chosen or Q to finish DISPLAY A: Athletics DISPLAY S: Swimming DISPLAY F: Football DISPLAY B: Badminton DISPLAY Enter data ACCEPT letter If letter = A then Athletics = athletics + 1 If letter = S then Swimming = Swimming + 1 If letter = F then Football = Football + 1 If letter = B then Badminton = Badminton + 1 UNTIL letter = Q DISLAY Athletics scored, athletics, votes DISLAY Swimming scored, swimming, votes DISLAY Football scored, football, votes DISLAY Badminton scored, Badminton, votes Example 12: Write a program that will output the square root of any number input until the number input is zero. In some cases, a variable has to be initialised before execution of the loop as shown in the following example. Use variable: number of type real DISPLAY Type in a number or zero to stop ACCEPT number WHILE number <> 0 Square = number * number DISPLAY The square of the number is, square DISPLAY Type in a number or zero to stop ACCEPT number ENDWHILE Example 14: Write a program to calculate the sum and average of a series of numbers. The pseudo-code solution is: Use variables: n, count of the type integer Sum, number, average of the type real DISPLAY How many numbers do you want to input ACCEPT count
Prepared by Om Prakash Mahato 8

Pseudocode, Algorithm and Flowchart


Computer Programming I

SUM = 0 FOR (n = 1, n <= count, n + 1) DISPLAY Input the number from your list ACCEPT number SUM = sum + number ENDFOR Average = sum / count DISPLAY The sum of the numbers is , sum DISPLAY Average of the numbers is , average

Function Calls in Pseudocode Calls to Functions should appear as: Call FunctionName (arguments: field1, field2, etc.) Returns in functions should appear as: Return (field1) Function headers should appear as: FunctionName (parameters: field1, field2, etc. ) While passing the addresses to Functions. Note that in C, arguments and parameters such as "fieldn" could be written: "pointer to fieldn ...." In Java, these could be references. Functions called with addresses should be written as: Call FunctionName (arguments: pointer to fieldn, pointer to field1, etc.) (or references to fields..) Function headers containing pointers should be indicated as: FunctionName (parameters: pointer to field1, pointer to field2, ...) Returns in functions where a pointer is returned: Return (pointer to fieldn) Parameters sent by Value (C, Java, .) is the default. If you are passing a pointer or a reference (C, Java), this should be explicitly indicated as above.

Recursive procedures Factorial A classic example of a recursive procedure is the function used to calculate the factorial of a natural number:

Pseudocode (recursive):

Prepared by Om Prakash Mahato

Pseudocode, Algorithm and Flowchart


Computer Programming I

function factorial is: input: integer n such that n >= 0 output: [n (n-1) (n-2) 1] 1. if n is 0, return 1 2. otherwise, return [ n factorial(n-1) ] end factorial This factorial function can also be described without using recursion by making use of the typical looping constructs found in imperative programming languages: Pseudocode (iterative): function factorial is: input: integer n such that n >= 0 output: [n (n-1) (n-2) 1] 1. create new variable called running_total with a value of 1 2. begin loop 1. if n is 0, exit loop 2. set running_total to (running_total n) 3. decrement n 4. repeat loop 3. return running_total end factorial Pseudocode for Array: The sorting is a good algorithm to use as a pseudocode example. This snippet will place the sort inside a function to provide a more extensive example and use c pseudocode as the basis for the code. Function sort (array []) For (i = 1 to length of array-1) For (j = i+1 to length of arrayi) If array[j] > array[j + 1] Swap array[j] and array [j + 1] End for End for End function NOTE: Just taking above Tips, Try to make Pseudocode for any program which you have done C. It is not difficult and do not be confused seing different examples done in different styles. There is no fixed rule for doing Pseudocode, only remember the guidelines as given above and do your Pseudocode as your style, it doesnt matter. The main thing is you should do the whole process as done in C code taking the above guidelines.

Prepared by Om Prakash Mahato

10

Pseudocode, Algorithm and Flowchart


Computer Programming I

Algorithm and Flowchart Example: Write algorithm and draw a flowchart for the following gerneratin following pattern. 1 1 2 1 1 2 3 2 1 1 2 3 Solution: Algorithm: 1. Start 2. Declare i,j,n 3. i=1 4. Read n 5. for i<=n Repeat 5.1 to 5.8 5.1 j=1 5.2 for j<=n-I Repeat 5.2.1 and 5.2.1 5.2.1 print blank space 5.2.2 j=j+1 5.3 j=1 5.4 for j<=1 Repeat 5.4.1 and 5.4.2 5.4.1 print j with horizontal tab 5.4.2 j=j+1 5.5 j=j-1 5.6 for j>=1 Repeat 5.6.1 and 5.6.2 5.6.1 print j with horizontal tab 5.6.2 j=j-1 5.7 change line 5.8 i=i+1 6 . stop
Start

4 3 2 1

---------------------------

Flowchart:
Declare i,j and n

Read n

Prepared by Om Prakash Mahato

11

You might also like