Like this document? Why not share!

3,497

Published on

MELJUN CORTES Algorithm Pseudo Code

No Downloads

Total Views

3,497

On Slideshare

0

From Embeds

0

Number of Embeds

0

Shares

0

Downloads

66

Comments

0

Likes

1

No embeds

No notes for slide

- 1. Pseudocode, Algorithm and Flowchart Computer Programming IAn algorithm is a procedure for solving a problem in terms of the actions to be executed andthe order in which those actions are to be executed. An algorithm is merely the sequence ofsteps 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 developalgorithms. 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 belowwill 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 programmingeffort. The purpose of pseudocode is to elaborate on the algorithmic detail and not just cite anabstraction.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.SEQUENCESequential control is indicated by writing one action after another, each action on a line byitself, 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 mirrorHow To WRITE PseudoCode?Example 1. READ height of rectangle 2. READ width of rectangle 3. COMPUTE area as height times widthCommon Action KeywordsSeveral keywords are often used to indicate common input, output, and processingoperations. Input: READ, OBTAIN, GET Output: PRINT, DISPLAY, SHOW Compute: COMPUTE, CALCULATE, DETERMINE Initialize: SET, INIT Add one: INCREMENT, BUMP Prepared by Om Prakash Mahato 1
- 2. Pseudocode, Algorithm and Flowchart Computer Programming IA 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 ofcomputation 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.875IF-THEN-ELSEBinary 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 ENDIFThe ELSE keyword and "sequence 2" are optional. If the condition is true, sequence 1 isperformed, otherwise sequence 2 is performed. Prepared by Om Prakash Mahato 2
- 3. Pseudocode, Algorithm and Flowchart Computer Programming IExampleCODE: SELECT ALL IF HoursWorked > NormalMax THEN Display overtime message ELSE Display regular time message ENDIFThe Repetition structure can be implemented using• Repeat Until Loop• The While Loop• The For LoopWHILEThe WHILE construct is used to specify a loop with a test at the top. The beginning andending of the loop are indicated by two keywords WHILE and ENDWHILE. The generalform is:CODE: SELECT ALL WHILE condition sequence ENDWHILEThe loop is entered only if the condition is true. The "sequence" is performed for eachiteration. At the conclusion of each iteration, the condition is evaluated and the loopcontinues as long as the condition is true.ExampleCODE: SELECT ALL WHILE Population < Limit Compute Population as Population + Births - Deaths ENDWHILEExampleCODE: SELECT ALL WHILE employee.type NOT EQUAL manager AND personCount < numEmployees INCREMENT personCount CALL employeeList.getPerson with personCount RETURNING employee ENDWHILECASEA CASE construct indicates a multiway branch based on conditions that are mutuallyexclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used toindicate the various alternatives. The general form is: Prepared by Om Prakash Mahato 3
- 4. Pseudocode, Algorithm and Flowchart Computer Programming ICODE: SELECT ALL CASE expression OF condition 1 : sequence 1 condition 2 : sequence 2 ... condition n : sequence n OTHERS: default sequence ENDCASEThe OTHERS clause with its default sequence is optional. Conditions are normally numbersor charactersindicating the value of "expression", but they can be English statements or some othernotation that specifies the condition under which the given sequence is to be performed. Acertain sequence may be associated with more than one condition.ExampleCODE: SELECT ALL CASE Title OF Mr : Print "Mister" Mrs : Print "Missus" Miss : Print "Miss" Ms : Print "Mizz" Dr : Print "Doctor" ENDCASEExampleCODE: SELECT ALL CASE grade OF A : points = 4 B : points = 3 C : points = 2 D : points = 1 F : points = 0 ENDCASEREPEAT-UNTILThis loop is similar to the WHILE loop except that the test is performed at the bottom of theloop instead of at the top. Two keywords, REPEAT and UNTIL are used. The general formis:CODE: SELECT ALL REPEAT sequence UNTIL condition Prepared by Om Prakash Mahato 4
- 5. Pseudocode, Algorithm and Flowchart Computer Programming IThe "sequence" in this type of loop is always performed at least once, because the test ispeformed after the sequence is executed. At the conclusion of each iteration, the condition isevaluated, and the loop repeats if the condition is false. The loop terminates when thecondition becomes true.FORThis 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 ENDFORIn cases where the loop constraints can be obviously inferred it is best to describe the loopusing problem domain vocabulary.ExampleCODE: 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 CONSTRUCTSThe 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.ExampleCODE: SELECT ALL SET total to zero REPEAT READ Temperature IF Temperature > Freezing THEN INCREMENT total END IF UNTIL Temperature < zero Print totalIn the above example, the IF construct is nested within the REPEAT construct, and thereforeis indented. Prepared by Om Prakash Mahato 5
- 6. Pseudocode, Algorithm and Flowchart Computer Programming IEXAMPLES of PseudoCodeExample 3: This is the pseudo-code required to input three numbers from the keyboardand output the result.Use variables: sum, number1, number2, number3 of type integerAccept number1, number2, number3Sum = number1 + number2 + number3Print sumEnd programExample 4: The following pseudo-code describes an algorithm which will accept twonumbers from the keyboard and calculate the sum and product displaying the answer onthe monitor screen.Use variables sum, product, number1, number2 of type realdisplay “Input two numbers”accept number1, number2sum = number1 + number2print “The sum is “, sumproduct = number1 * number2print “The Product is “, productend programNote: -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 toLOGICAL OPERATORS: AND, OR, NOTAND: if any of the conditions are false, the whole expression is false.ex: IF day = “Saturday” AND weather = “sunny”WRITE “Let‟s go to the beach!”ENDIFOR: if any of the conditions are true, the whole expression is trueex: IF month = “June” OR month = “July” OR month = “August”WRITE “Yahoo! Summer vacation!”ENDIFNOT: reverses the outcome of the expression; true becomes false, false becomes true.ex: IF day <> “Saturday” AND day <> “Sunday”WRITE “Yuk, another work day”ENDIFExample 5: The following shows how the selection control structure is used in a programwhere a user chooses the options for multiplying the numbers or adding them orsubtracting.Use variables: choice, of the type characterans, number1, number2, of type integerdisplay “choose one of the following”display “m for multiply”display “a for add” Prepared by Om Prakash Mahato 6
- 7. Pseudocode, Algorithm and Flowchart Computer Programming Idisplay “s for subtract”accept choicedisplay “input two numbers you want to use”accept number1, number2if choice = m then ans = number1 * number2if choice = a then ans = number1 + number2if choice = s then ans = number1 - number2display ansExample 6: The program is to input a examination mark and test it for the award of agrade. The mark is a whole number between 1 and 100. Grades are awarded according tothe following criteria:>= 80 Distinction>= 60 Merit>= 40 Pass< 40 failThe pseudo-code isUse variables: mark of type integerIf 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 screendescribing the insurance available according to a category input by the user.Use variables: category of type characterDisplay “input category”Accept categoryIf category = U Display “insurance is not available”ElseIf category = A then Display “insurance is double”ElseIf category = B then Display “insurance is normal”ElseIf 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 characterDisplay “input category”Accept categoryDO case of categoryCASE category = U Display “insurance not available”CASE category = A Display “insurance is double”CASE category = B Prepared by Om Prakash Mahato 7
- 8. Pseudocode, Algorithm and Flowchart Computer Programming I Display “insurance is normal”CASE category = M Display “insurance is medically dependent”OTHERWISE: Display “entry is invalid”ENDCASEInstead of using the word otherwise, one can use else.Example 10. A survey has been carried out to discover the most popular sport. Theresults will be typed into the computer for analysis. Write a program to accomplish this.REPEATDISPLAY “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 letterIf letter = „A‟ then Athletics = athletics + 1If letter = „S‟ then Swimming = Swimming + 1If letter = „F‟ then Football = Football + 1If letter = „B‟ then Badminton = Badminton + 1UNTIL 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 untilthe number input is zero.In some cases, a variable has to be initialised before execution of the loop as shown inthe following example.Use variable: number of type realDISPLAY “Type in a number or zero to stop”ACCEPT numberWHILE number <> 0 Square = number * number DISPLAY “The square of the number is”, square DISPLAY “Type in a number or zero to stop” ACCEPT numberENDWHILEExample 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 integerSum, number, average of the type realDISPLAY “How many numbers do you want to input”ACCEPT count Prepared by Om Prakash Mahato 8
- 9. Pseudocode, Algorithm and Flowchart Computer Programming ISUM = 0FOR (n = 1, n <= count, n + 1) DISPLAY “Input the number from your list” ACCEPT number SUM = sum + numberENDFORAverage = sum / countDISPLAY “The sum of the numbers is “, sumDISPLAY “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 proceduresFactorialA classic example of a recursive procedure is the function used to calculate the factorial of anatural number:Pseudocode (recursive): Prepared by Om Prakash Mahato 9
- 10. Pseudocode, Algorithm and Flowchart Computer Programming Ifunction factorial is:input: integer n such that n >= 0output: [n × (n-1) × (n-2) × … × 1] 1. if n is 0, return 1 2. otherwise, return [ n × factorial(n-1) ]end factorialThis factorial function can also be described without using recursion by making use of thetypical looping constructs found in imperative programming languages:Pseudocode (iterative):function factorial is:input: integer n such that n >= 0output: [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_totalend factorialPseudocode for Array:The sorting is a good algorithm to use as a pseudocode example. This snippet will place thesort inside a function to provide a more extensive example and use c pseudocode as the basisfor 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 forEnd forEnd functionNOTE: Just taking above Tips, Try to make Pseudocode for any program which you havedone C. It is not difficult and do not be confused seing different examples done in differentstyles. There is no fixed rule for doing Pseudocode, only remember the guidelines as givenabove and do your Pseudocode as your style, it doesn‟t matter. The main thing is you shoulddo the whole process as done in C code taking the above guidelines. Prepared by Om Prakash Mahato 10
- 11. Pseudocode, Algorithm and Flowchart Computer Programming IAlgorithm and FlowchartExample: Write algorithm and draw a flowchart for the following gerneratin followingpattern. 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 ---------------------------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 StartFlowchart: Declare i,j and n Read n Prepared by Om Prakash Mahato 11

Be the first to comment