Pseudo Code Algorithm Flowchart | Control Flow - baixardoc
-
Upload
khangminh22 -
Category
Documents
-
view
1 -
download
0
Transcript of Pseudo Code Algorithm Flowchart | Control Flow - baixardoc
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 11
An algorithm is a procedure for solving a problem in terms of An algorithm is a procedure for solving a problem in terms of the actions to be executed andthe actions to be executed and
the order in which the order in which those actions are to be those actions are to be executed. An algorithm is merely the executed. An algorithm is merely the sequence of sequence of
steps taken to solve a steps taken to solve a problem. The steps are normally "sequence," "selection, " "iproblem. The steps are normally "sequence," "selection, " "i teration,"teration,"
and a case-type statement.and a case-type statement.
In C, "sequence statements" are imperatives. The "selection" is tIn C, "sequence statements" are imperatives. The "selection" is the "if then he "if then else" statement,else" statement,
and the iteration is satisfied by a number of statements, such as the "while," " do," and the iteration is satisfied by a number of statements, such as the "while," " do," and theand the
"for," while the "for," while the case-type statement is satisfied by the "switch" case-type statement is satisfied by the "switch" statement.statement.
Pseudocode is an artificial and informal language that Pseudocode is an artificial and informal language that helps programmers to develophelps programmers to develop
algorithms. Pseudocodalgorithms. Pseudocode is a e is a "text-based" detail (algorithmic) design tool."text-based" detail (algorithmic) design tool.
The rules of Pseudocode are reasonably straightforward. All statements showingThe rules of Pseudocode are reasonably straightforward. All statements showing
"dependency"dependency" are to " are to be indented. These include while, do, for, be indented. These include while, do, for, if, switch. Examples belowif, switch. Examples below
will illustrate this notion.will illustrate this notion.
GUIDE TO PSEUDOCODE LEVEL OF DETAIL: Given GUIDE TO PSEUDOCODE LEVEL OF DETAIL: Given record/file descriptions,record/file descriptions,
pseudocodpseudocode should be created in e should be created in sufficient detail so as sufficient detail so as to directly support the programmingto directly support the programming
effort. The purpose of pseudocode is to elaborate on the algorithmic detail and not just cite aneffort. The purpose of pseudocode is to elaborate on the algorithmic detail and not just cite an
abstraction.abstraction.
There is not fixed rule for writing the PseudoCoThere is not fixed rule for writing the PseudoCode. de. It differers from one company to another,It differers from one company to another,
however there is certain basic Pseudocode standard as follows:however there is certain basic Pseudocode standard as follows:
1.1. Write only one statement per line.Write only one statement per line.
2.2. Capitalize keyword used for Pseudocode, like READ, PRINT etcCapitalize keyword used for Pseudocode, like READ, PRINT etc
3.3. Start all the sequences from same cStart all the sequences from same column in case olumn in case of without use of selection(i.e. bodyof without use of selection(i.e. body
of if, for , while etc)of if, for , while etc)
4.4. Make Pseudocode as Programming language independent.Make Pseudocode as Programming language independent.
SEQUENCESEQUENCE
Sequential control is indicated by writing one action after another, each action on a line bySequential 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 sequenceitself, and all actions aligned with the same indent. The actions are performed in the sequence
(top to bottom) that they are writt(top to bottom) that they are written.en.
Example (non-computer)Example (non-computer)
1.1. Brush teethBrush teeth
2.2. Wash faceWash face
3.3. Comb hairComb hair
4.4. Smile in mirrorSmile in mirror
How To WRITE PseudoCode?How To WRITE PseudoCode?
ExampleExample
1.1. READ height of rectangleREAD height of rectangle
2.2. READ width of rectangleREAD width of rectangle
3.3. COMPUTE area as height times widthCOMPUTE area as height times width
Common Action KeywordsCommon Action Keywords
Several keywords are often used to indicate common Several keywords are often used to indicate common input, output, and processinginput, output, and processing
operations.operations.
Input: READ, OBTAIN, GETInput: READ, OBTAIN, GET Output: PRINT, DISPLAY, SHOWOutput: PRINT, DISPLAY, SHOW Compute: COMPUTE, CALCULATE, DETERMINECompute: COMPUTE, CALCULATE, DETERMINE Initialize: SET, INITInitialize: SET, INIT Add one: INCREMENT, BUMPAdd one: INCREMENT, BUMP
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 22
A computer can perform arithmetic A computer can perform arithmetic operation.operation.
A programmer may use actual mathematical symbols or A programmer may use actual mathematical symbols or the words for those the words for those symbols.symbols.
For example: "Add score to For example: "Add score to total_score" is same as "total_score = total_score + total_score" is same as "total_score = total_score + score"score"
(programming languages use mathematical equations to assign values to memory(programming languages use mathematical equations to assign values to memory
locations. In this case, a new locations. In this case, a new value of total_score is assigned to a value of total_score is assigned to a memory locationmemory location
named total_score by adding score to the current named total_score by adding score to the current (not new) value of (not new) value of total_score)total_score)
The following symbols can be used in pseudocodThe following symbols can be used in pseudocode: + for Add, - e: + for Add, - for Subtract, * forfor Subtract, * for
Multiply, / for Divide, ( ) Multiply, / for Divide, ( ) for Parenthesesfor Parentheses For more example:For more example:
oo Divide total_score by student_countDivide total_score by student_count
oo class_aveclass_average = rage = total_score / total_score / student_countstudent_count
oo Compute C = (F - 32) * 5 / 9Compute C = (F - 32) * 5 / 9
When writing mathematical calculation for the When writing mathematical calculation for the computer, the order of operationcomputer, the order of operation
should be considered; otherwise you may end up witshould be considered; otherwise you may end up with incorrect values.h incorrect values. The order of operators are The order of operators are following:following:
1.1. ( ) : Values within parentheses are always evaluated first.( ) : Values within parentheses are always evaluated first.
2.2. ^ : Exponentiation (raising a number to a power) is second.^ : Exponentiation (raising a number to a power) is second.
3.3. - : Negation (creating a negative number) is third.- : Negation (creating a negative number) is third.
4.4. * and / : Multiplication or division i* and / : Multiplication or division is fourth.s fourth.
5.5. \ : Integer division (a.k.a. Div) is fift \ : Integer division (a.k.a. Div) is fifth.h.
6.6. Mod : Remainder division is sixth.Mod : Remainder division is sixth.
7.7. + or - : Addition + or - : Addition and subtraction are last.and subtraction are last.
Example: For an expression Total = 10 + 15 * 2 / Example: For an expression Total = 10 + 15 * 2 / 4 ^ 2 -(2 4 ^ 2 -(2 + 3) , the order of + 3) , the order of
computation is following:computation is following:
0.0. Total = 10 + 15 * 2 / 4 ^ 2 -(Total = 10 + 15 * 2 / 4 ^ 2 -( 2 + 32 + 3))
1.1. Total = 10 + 15 * 2 / Total = 10 + 15 * 2 / 4 ^ 24 ^ 2 -(5)-(5)
2.2. Total = 10 + 15 * 2 / 16Total = 10 + 15 * 2 / 16 -(5)-(5) ( 5 as a negative value)( 5 as a negative value)
3.3. Total = 10 +Total = 10 + 15 * 215 * 2 / 16 - 5 / 16 - 5
4.4. Total = 10 +Total = 10 + 30 / 1630 / 16 - 5- 5
5.5. Total =Total = 10 + 1.87510 + 1.875 - 5- 5
6.6. Total =Total = 11.875 - 511.875 - 5
7.7. Total = 6.875Total = 6.875
IF-THEN-ELSEIF-THEN-ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords: IF,Binary choice on a given Boolean condition is indicated by the use of four keywords: IF,
THEN, ELSE, and ENDIF. The general form THEN, ELSE, and ENDIF. The general form is:is:
CODE:CODE: SELECT ALLSELECT ALL
IF condition THENIF condition THEN
sequence 1sequence 1
ELSEELSE
sequence 2sequence 2
ENDIFENDIF
The ELSE keyword and "sequencThe ELSE keyword and "sequence 2" are optional. If the condition e 2" are optional. If the condition is true, sequence 1 isis true, sequence 1 is
performed, otherwise sequence 2 is performed, otherwise sequence 2 is performed.performed.
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 33
ExampleExample
CODE:CODE: SELECT ALLSELECT ALL
IF HoursWorked > NormalMax THENIF HoursWorked > NormalMax THEN
Display overtime messageDisplay overtime message
ELSEELSE
Display regular time messageDisplay regular time message
ENDIFENDIF
The Repetition structure can be implemented usingThe Repetition structure can be implemented using
•• Repeat Until LoopRepeat Until Loop
•• The While LoopThe While Loop
•• The For LoopThe For Loop
WHILEWHILE
The WHILE construct is used to specify a loop with a test at The WHILE construct is used to specify a loop with a test at the top. The beginning andthe top. The beginning and
ending of the loop are ending of the loop are indicated by two keywords WHILE and ENDWHILE. indicated by two keywords WHILE and ENDWHILE. The generalThe general
form is:form is:
CODE:CODE: SELECT ALLSELECT ALL
WHILE conditionWHILE condition
sequencesequence
ENDWHILEENDWHILE
The loop is entered only if the condition is true. The "sequence" is performed for eachThe 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 loopiteration. At the conclusion of each iteration, the condition is evaluated and the loop
continues as long as the condition is true.continues as long as the condition is true.
ExampleExample
CODECODE:: SELECT ALLSELECT ALL
WHILE Population < LimitWHILE Population < Limit
Compute Population as Population + Births - Compute Population as Population + Births - DeathsDeaths
ENDWHILEENDWHILE
ExampleExample
CODE:CODE: SELECT ALLSELECT ALL
WHILE employee.type NOT EQUAL manager AND WHILE employee.type NOT EQUAL manager AND personCount < numEmployeespersonCount < numEmployees
INCREMENT personCountINCREMENT personCount
CALL employeeList.getPeCALL employeeList.getPerson with rson with personCount RETURNING employeepersonCount RETURNING employee
ENDWHILEENDWHILE
CASECASE
A CASE construct indicates a multiway branch based on conditions that are mutuallyA CASE construct indicates a multiway branch based on conditions that are mutually
exclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used toexclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used to
indicate the various alternatives. The general form indicate the various alternatives. The general form is:is:
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 44
CODE:CODE: SELECT ALLSELECT ALL
CASE expression OFCASE expression OF
condition 1 : sequence 1condition 1 : sequence 1
condition 2 : sequence 2condition 2 : sequence 2
......
condition n : sequence ncondition n : sequence n
OTHERS:OTHERS:
default sequencedefault sequence
ENDCASEENDCASE
The OTHERS clause with its The OTHERS clause with its default sequence is optional. Conditions are normally numbersdefault sequence is optional. Conditions are normally numbers
or charactersor characters
indicating the value of "expression", but they indicating the value of "expression", but they can be English statements or some othercan be English statements or some other
notation that specifies the condition under which tnotation that specifies the condition under which the given sequence is to be he given sequence is to be performed. Aperformed. A
certain sequence may be associated with more than one condition.certain sequence may be associated with more than one condition.
ExampleExample
CODE:CODE: SELECT ALLSELECT ALL
CASE Title OFCASE Title OF
Mr Mr : : Print Print "Mister""Mister"
Mrs Mrs : : Print Print "Missus""Missus"
Miss Miss : : Print Print "Miss""Miss"
Ms Ms : : Print Print "Mizz""Mizz"
Dr Dr : : Print Print "Doctor""Doctor"
ENDCASEENDCASE
ExampleExample
CODE:CODE: SELECT ALLSELECT ALL
CASE grade OFCASE grade OF
A A : : points points = = 44
B B : : points points = = 33
C C : : points points = = 22
D D : : points points = = 11
F F : : points points = = 00
ENDCASEENDCASE
REPEAT-UNTILREPEAT-UNTIL
This loop is similar to the WThis loop is similar to the WHILE loop except that the test is performed at the bottom HILE loop except that the test is performed at the bottom of theof the
loop instead of at loop instead of at the top. Two keywords, REPEAT and UNTIL the top. Two keywords, REPEAT and UNTIL are used. The general formare used. The general form
is:is:
CODE:CODE: SELECT ALLSELECT ALL
REPEATREPEAT
sequencesequence
UNTIL conditionUNTIL condition
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 55
The "sequence" in this type of loop is always performed at least once, because the test isThe "sequence" in this type of loop is always performed at least once, because the test is
peformed after the sequence is executed. At the peformed after the sequence is executed. At the conclusion of each iteration, the condition isconclusion of each iteration, the condition is
evaluated, and the loop repeats if the condition is false. The loop terminates when theevaluated, and the loop repeats if the condition is false. The loop terminates when the
condition becomes true.condition becomes true.
FORFOR
This loop is a specialized construct for iterating a specific number of times, often called aThis loop is a specialized construct for iterating a specific number of times, often called a
"counting" loop. "counting" loop. Two keywords, FOTwo keywords, FOR and ENDFOR are used. The geneR and ENDFOR are used. The general form is:ral form is:
CODE:CODE: SELECT ALLSELECT ALL
FOR iteration boundsFOR iteration bounds
sequencesequence
ENDFORENDFOR
In cases where the loop constraints can be obviously inferred it is best to describe the loopIn cases where the loop constraints can be obviously inferred it is best to describe the loop
using problem domain vocabulary.using problem domain vocabulary.
ExampleExample
CODE:CODE: SELECT ALLSELECT ALL
FOR each month of the FOR each month of the year (good)year (good)
FOR month = 1 to 12 (ok)FOR month = 1 to 12 (ok)
FOR each employee in the list FOR each employee in the list (good)(good)
FOR empno = 1 to listsize (ok)FOR empno = 1 to listsize (ok)
NESTED CONSTRUCTSNESTED CONSTRUCTS
The constructs can be embedded within each other, and this The constructs can be embedded within each other, and this is made clear by use of is made clear by use of indenting.indenting.
Nested constructs should be clearly indented from their Nested constructs should be clearly indented from their surrounding constructs.surrounding constructs.
ExampleExample
CODE:CODE: SELECT ALLSELECT ALL
SET total to zeroSET total to zero
REPEATREPEAT
READ TemperatureREAD Temperature
IF Temperature > Freezing THENIF Temperature > Freezing THEN
INCREMENT totalINCREMENT total
END IFEND IF
UNTIL Temperature < zeroUNTIL Temperature < zero
Print totalPrint total
In the above example, the In the above example, the IF construct is nested within IF construct is nested within the REPEAT construct, and thereforethe REPEAT construct, and therefore
is indented.is indented.
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 66
EXAMPLES of PseudoCodeEXAMPLES of PseudoCode
Example 3: This is Example 3: This is the pseudo-code required to input three numbers from the pseudo-code required to input three numbers from the keyboardthe keyboard
and output the result.and output the result.
Use variables: sum, number1, number2, number3 of type integer Use variables: sum, number1, number2, number3 of type integer
Accept number1, number2, number3 Accept number1, number2, number3
Sum = number1 + number2 + number3Sum = number1 + number2 + number3
Print sumPrint sum
End program End program
Example 4: The following pseudo-code describes an algorithm which will Example 4: The following pseudo-code describes an algorithm which will accept twoaccept two
numbers from the keyboard and calculate the sum numbers from the keyboard and calculate the sum and product displaying the answer onand product displaying the answer on
the monitor screen.the monitor screen.
Use variables sum, product, number1, number2 of type realUse variables sum, product, number1, number2 of type real
display “Input two numbers”display “Input two numbers”accept number1, number2accept number1, number2
sum = number1 + number2sum = number1 + number2
print “The sum is “, sum print “The sum is “, sum
product = number1 * number2 product = number1 * number2
print “The Product is “, print “The Product is “, product product
end programend program
Note: -The logical operators used in Note: -The logical operators used in our pseudo-code areour pseudo-code are
= is equal to= is equal to
> is greater than> is greater than
< is less than< is less than
>= is greater than or equal>= is greater than or equal
<= is less than or equal<= is less than or equal
<> is not eaqual to<> is not eaqual to
LOGICAL OPERATORS: AND, OR, NOTLOGICAL OPERATORS: AND, OR, NOT
AND: if any of the conditions are false, the whole expression is false.AND: if any of the conditions are false, the whole expression is false.
ex: IF day = “Saturdaex: IF day = “Saturday” AND weather = “sunny”y” AND weather = “sunny”
WRITE “Let‟s go to the beach!”WRITE “Let‟s go to the beach!”
ENDIFENDIF
OR: if any of the conditions are true, the whole expression is trueOR: if any of the conditions are true, the whole expression is true
ex: IF month = “June” OR ex: IF month = “June” OR month = “July” OR month = month = “July” OR month = “August”“August”
WRITE “Yahoo! Summer vacation!”WRITE “Yahoo! Summer vacation!”
ENDIFENDIF
NOT: reverses the outcome of the NOT: reverses the outcome of the expression; true becomes false, false becomes true.expression; true becomes false, false becomes true.
ex: IF day <> ex: IF day <> “Saturday” AND day <> “Sunday”“Saturday” AND day <> “Sunday”
WRITE “Yuk, another work day”WRITE “Yuk, another work day”
ENDIFENDIF
Example 5: The following shows how the selection control structure is used in a programExample 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 orwhere a user chooses the options for multiplying the numbers or adding them or
subtracting.subtracting.Use variables: choice, of the type character Use variables: choice, of the type character
ans, number1, number2, of type integer ans, number1, number2, of type integer
displaydisplay “choose one of the following”“choose one of the following”
display “m for multiply”display “m for multiply”display “a for add”display “a for add”
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 77
display “s for subtract”display “s for subtract”accept choiceaccept choice
display “input two numbers you want to use”display “input two numbers you want to use”
accept number1, number2accept number1, number2
if choice = m then ans = number1 * number2if choice = m then ans = number1 * number2
if choice = a then ans = number1 + number2if choice = a then ans = number1 + number2
if choice = s then ans = number1 - number2if choice = s then ans = number1 - number2
display ansdisplay ans
Example 6: The program is to input a examination mark and test it Example 6: The program is to input a examination mark and test it for the award of afor the award of a
grade. The mark is a grade. The mark is a whole number between 1 and 100. whole number between 1 and 100. Grades are awarded according toGrades are awarded according to
the following criteria:the following criteria:
>= 80 Distinction>= 80 Distinction
>= 60 Merit>= 60 Merit
>= 40 Pass>= 40 Pass
< 40 fail< 40 fail
The pseudo-code isThe pseudo-code is
Use variables: mark of type integer Use variables: mark of type integer
If mark >= 80 display “distinction” If mark >= 80 display “distinction”
If mark >= 60 and mark < 80 display “merit” If mark >= 60 and mark < 80 display “merit” If mark >= 40 and mark < 60 display “pass” If mark >= 40 and mark < 60 display “pass”
If mark < 40 display If mark < 40 display “fail”“fail”
Example 8: The following program segment outputs Example 8: The following program segment outputs a message to the monitor a message to the monitor screenscreen
describing the insurance available according to a category input by thdescribing the insurance available according to a category input by the user.e user.
Use variables: category of type character Use variables: category of type character
Display “input category” Display “input category” Accept category Accept category
If category = U If category = U
Display “insurance is not available” Display “insurance is not available” Else Else
If category = A then If category = A then
Display “insurance is double” Display “insurance is double” Else Else
If category = B then If category = B then
Display “insurance is normal” Display “insurance is normal” Else Else
If category = M then If category = M then
Display “insurance is medically dependent” Display “insurance is medically dependent” Else Else
Display “entry invalid” Display “entry invalid”
This can be expressed in a This can be expressed in a case statement as follows:case statement as follows:
Use variables: category of type character Use variables: category of type character
Display “input category” Display “input category” Accept category Accept category
DO case of category DO case of category
CASE category = U CASE category = U
Display “insurance not available” Display “insurance not available”CASE category = ACASE category = A
Display “insurance is double” Display “insurance is double”CASE category = BCASE category = B
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 88
Display “insurance is normal” Display “insurance is normal”CASE category = M CASE category = M
Display “insurance is medically dependent” Display “insurance is medically dependent”OTHERWISE:OTHERWISE:
Display “entry is invalid” Display “entry is invalid” ENDCASE ENDCASE
Instead of using the wordInstead of using the word otherwiseotherwise, one can use, one can use elseelse..
Example 10. A survey has been carried out to discover the most popular sport. TheExample 10. A survey has been carried out to discover the most popular sport. The
results will be typed into the computer for analysis. Write results will be typed into the computer for analysis. Write a program to accomplish this.a program to accomplish this. REPEAT REPEAT
DISPLAY “Type in the letter chosen or Q to finish” DISPLAY “Type in the letter chosen or Q to finish” DISPLAY “A: DISPLAY “A: AthleticsAthletics””
DISPLAY “S: Swimming” DISPLAY “S: Swimming” DISPLAY “F: Football” DISPLAY “F: Football”
DISPLAY “B: DISPLAY “B: BadmintonBadminton””
DISPLAY “Enter data” DISPLAY “Enter data” ACCEPT letter ACCEPT letter
If letter = „A‟ then If letter = „A‟ then Athletics = athletics + 1 Athletics = athletics + 1
If letter = „S‟ then If letter = „S‟ thenSwimming = Swimming + 1Swimming = Swimming + 1
If letter = „F‟ then If letter = „F‟ thenFootball = Football + 1Football = Football + 1
If letter = „B‟ then If letter = „B‟ then Badminton = Badminton + 1 Badminton = Badminton + 1
UNTILUNTIL letter = „Q‟ letter = „Q‟
DISLAY “Athletics scored”, athletics, “votes” DISLAY “Athletics scored”, athletics, “votes” DISLAY “Swimming scored”, swimming, “votes” DISLAY “Swimming scored”, swimming, “votes”
DISLAY “Football scored”, football, “votes” DISLAY “Football scored”, football, “votes”
DISLAY “Badminton scored”, Badminton, “votes” DISLAY “Badminton scored”, Badminton, “votes”
Example 12: Write a program that will output Example 12: Write a program that will output the square root of any number input untilthe square root of any number input until
the number input is zero.the number input is zero.
In some cases, a variable has to be initialised before execution of the loop as shown inIn some cases, a variable has to be initialised before execution of the loop as shown in
the following example.the following example.
Use variable: number of type realUse variable: number of type real
DISPLAY “Type in a number or zero to stop” DISPLAY “Type in a number or zero to stop” ACCEPT number ACCEPT number
WHILE number <> 0WHILE number <> 0
Square = number * number Square = number * number
DISPLAY “The square of the number is”, square DISPLAY “The square of the number is”, square DISPLAY “Type in a number or zero to stop” DISPLAY “Type in a number or zero to stop”
ACCEPT number ACCEPT number
ENDWHILE ENDWHILE
Example 14: Write a program to calculate the sum and average of a series of numbers.Example 14: Write a program to calculate the sum and average of a series of numbers.
The pseudo-code solution is:The pseudo-code solution is:
Use variables: n, count of the type integer Use variables: n, count of the type integer
Sum, number, average of the type realSum, number, average of the type real
DISPLAY “How many numbers do you want to input” DISPLAY “How many numbers do you want to input” ACCEPT count ACCEPT count
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 99
SUM = 0SUM = 0
FOR (n = 1, n <= count, n + 1)FOR (n = 1, n <= count, n + 1)
DISPLAY “Input the number from your list” DISPLAY “Input the number from your list” ACCEPT number ACCEPT number
SUM = sum + number SUM = sum + number
ENDFOR ENDFOR
Average = sum / count Average = sum / count
DISPLAY “The sum of the numbers is “, sum DISPLAY “The sum of the numbers is “, sum
DISPLAY “Average of the numbers is “, average DISPLAY “Average of the numbers is “, average
Function Function Calls in Calls in PseudocodePseudocode
· · Calls to Calls to Functions Functions should ashould appear asppear as::
Call FunctionName (arguments: field1, field2, etc.)Call FunctionName (arguments: field1, field2, etc.)
· · Returns in Returns in functions functions should apshould appear as:pear as:
Return (field1) Return (field1)
· · Function Function headers headers should ashould appear appear as:s:
FunctionName (parameters: field1, field2, etc. )FunctionName (parameters: field1, field2, etc. )
·· While passing the addresses to Functions.While passing the addresses to Functions.
Note that in C, arguments and parameters such as "fieldn" could be written: "pointer to Note that in C, arguments and parameters such as "fieldn" could be written: "pointer to fieldnfieldn
...."...."
In Java, these could be „references.‟In Java, these could be „references.‟
· · Functions Functions called with addrecalled with addresses shosses should be written uld be written as:as:
Call FunctionName (arguments: pointer to fieldn, pointer to field1, etc.)Call FunctionName (arguments: pointer to fieldn, pointer to field1, etc.)
(or references to fields…..)(or references to fields…..)
· · Function hFunction headers containing eaders containing pointers shoupointers should be indicateld be indicated as:d as:
FunctionName (parameters: pointer to field1, pointer to field2, ...)FunctionName (parameters: pointer to field1, pointer to field2, ...)
· · Returns in Returns in functions functions where a where a pointer is pointer is returned:returned:
Return (pointer to fieldn) Return (pointer to fieldn)
Parameters sent „by Value‟ (C, Java, ….) is the def Parameters sent „by Value‟ (C, Java, ….) is the def ault. ault. If you If you are pasare passing a sing a pointerpointer
or a reference (C, or a reference (C, Java), this should be explicitly indicated as above.Java), this should be explicitly indicated as above.
Recursive proceduresRecursive procedures
FactorialFactorial
A classic example of a A classic example of a recursive procedure is the function used to recursive procedure is the function used to calculate thecalculate the factorialfactorial of aof a
natural number:natural number:
PseudocodePseudocode (recursive):(recursive):
Pseudocode, Algorithm and FlowchartPseudocode, Algorithm and FlowchartComputer Programming IComputer Programming I
Prepared byPrepared by Om Prakash MahatoOm Prakash Mahato 1010
unction factorial is:unction factorial is:
input: integer n such that n >= 0input: integer n such that n >= 0
output: [n × (n-1) × (n-output: [n × (n-1) × (n-2) × … × 1]2) × … × 1]1. if n is 0, return 11. if n is 0, return 1
2. otherwise, return [ n × factorial(n-1) ]2. otherwise, return [ n × factorial(n-1) ]
end factorialend factorial
This factorial function can also be This factorial function can also be described without using recursion by making use of thdescribed without using recursion by making use of thee
typical looping constructs found in typical looping constructs found in imperative programming languages:imperative programming languages:
Pseudocode (iterative):Pseudocode (iterative):
unction factorial is:unction factorial is:
input: integer n such that n >= 0input: integer n such that n >= 0
output: [n × (n-1) × (n-output: [n × (n-1) × (n-2) × … × 1]2) × … × 1]
1. create new variable called running_total with a value of 11. create new variable called running_total with a value of 1
2. begin loop2. begin loop
1. if n is 0, exit loop1. if n is 0, exit loop
2. set running_total to (running_total × n)2. set running_total to (running_total × n)
3. decrement n3. decrement n
4. repeat loop4. repeat loop
3. return running_total3. return running_total
end factorialend factorial
Pseudocode for Array:Pseudocode for Array:
The sorting is a good algorithm to use as a pseudocode example. This snippet will place theThe sorting is a good algorithm to use as a pseudocode example. This snippet will place the
sort inside a function to provide a more extesort inside a function to provide a more extensive example and usnsive example and use c e c pseudocode apseudocode as the basiss the basis
for the code.for the code.
Function sort (array [])Function sort (array [])
For (i = 1 to length of array-1)For (i = 1 to length of array-1)
For (j = i+1 to length of arrayi)For (j = i+1 to length of arrayi)
If array[j] > array[j + 1] If array[j] > array[j + 1]
Swap array[j] and array [j + 1]Swap array[j] and array [j + 1]
End for End for
End for End for
End function End function
NOTE: NOTE: Just taking above Tips, Try to Just taking above Tips, Try to make Pseudocode for any program which you havemake Pseudocode for any program which you have
done C. It is not difficult done C. It is not difficult and do not be confused seing different examples done in differentand do not be confused seing different examples done in different
styles. There is no fixed styles. There is no fixed rule for doing rule for doing PseudocodPseudocode, only remember the e, only remember the guidelines as givenguidelines as given
above and do your Pseudocode as your style, it doesnabove and do your Pseudocode as your style, it doesn ‟‟t matter. The main thing is t matter. The main thing is you shouldyou should
do the whole process as done ido the whole process as done in C code taking the n C code taking the above guidelines.above guidelines.