Wednesday, July 25, 2012

Psuedocode Examples

Pseudocode is an artificial and informal language that helps programmers 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.  Do not include data declarations in your pseudocode.
Examples:

1.
If student's grade is greater than or equal to 60
Print "passed"
else
Print "failed"

2.
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Set the class average to the total divided by ten
Print the class average.

3.
Initialize total to zero
Initialize counter to zero
Input the first grade
while the user has not as yet entered the sentinel
add this grade into the running total
add one to the grade counter
input the next grade (possibly the sentinel)

if the counter is not equal to zero
set the average to the total divided by the counter
print the average
else
print 'no grades were entered'

4.
initialize passes to zero
initialize failures to zero
initialize student to one
while student counter is less than or equal to ten

input the next exam result
if the student passed

add one to passes
else
add one to failures

add one to student counter
print the number of passes
print the number of failures

if eight or more students passed
print "raise tuition"

(Initialize passes to zero: set variables to zero
Initialize failures to zero: set variables to zero
Initialize students to one: set variables to one
While student counter is less than or equal to ten: repeat/loop

input the next exam result
if the student passed
add one to passses
else
add one to to failures)

For looping and selection, The keywords that are to be used include Do While...EndDo; Do Until...Enddo; Case...EndCase; If...Endif; Call ... with (parameters); Call; Return ....; Return; When; Always use scope terminators for loops and iteration.
As verbs, use the words Generate, Compute, Process, etc. Words such as set, reset, increment, compute, calculate, add, sum, multiply, ... print, display, input, output, edit, test , etc. with careful indentation tend to foster desirable pseudocode. '

Selection:
- If
- Then
- Else

Command:
- Print: output to hard copy
- Input: get value
- Initialize: set value

Repetition:
- Repeat until .....
- Pretest repetition
- Post test repetition

Own example: Filling a bath with 80L

Begin
Initialize volume = 0
Turn on tap

Repeat
wait 30 seconds
until volume = 80

turn off tap

No comments:

Post a Comment