Professional Documents
Culture Documents
3 Pseudocode
3 Pseudocode
Sequence
The program is executed top –
down.
Selection: For single alternative, use
the IFTHEN-structure
The following calculates an employee’s WAGES given his hourly
RATE of pay and the number of HOURS worked.
read NAME, RATE, HOURS
WAGES = HOURS * RATE
IF HOURS > 40
WAGES = WAGES + (HOURS – 40) * 0.5 * RATE
ENDIF
write NAME, WAGES
END
Selection: For double alternative, use the IFTHENELSE-
structure
The following reads two numbers A and B and prints them in decreasing order.
read A, B
IF A < B
BIG = B
SMALL = A
ELSE
BIG = A
SMALL = B
ENDIF
Write BIG, SMALL
END
Selection: For multiple alternatives, use the ELSEIF-
structure. This is also called the NESTEDIF structure.
The following does what?
read A, B, C
D = B2 – 4*A*C
IF D > 0
X1 = (-B+D^0.5)/(2*A)
X2 = (-B-D^0.5)/(2*A)
write X1, X2
ELSEIF D = 0
X = -B/(2*A)
write ‘UNIQUE SOLUTION”, X
ELSE
write ‘NO REAL SOLUTION’
ENDIF
END
Repetitions: DO-loop
What does this do?
read N
DO K = 1 to N by 2
L = K2
write K, L
ENDDO
END
Repetitions: DOWHILE-loop (may not
do at all)
read N
K=1
DOWHILE K <= N
L = K2
write K, L
K=K+2
ENDDO
END
Repetitions: DOUNTIL-loop
read N
K=1
DOUNTIL K > N
L = K2
write K, L
K=K+2
ENDDO
END
Exercises
1. A salesman’s commission is 5% of his total
weekly sales, with an extra $100 if the sales
exceed $10000. Write a pseudocode program
which identifies a salesman and calculates his
commission.
2. Each record in a student file contains, among other data, the student’s
NAME and HEIGHT. The following program uses a DOUNTIL-loop to find
the name and height of the tallest student.
TALL = 0
TALLMAN = ‘JOHN’
read NAME, HEIGHT
DOUNTIL End of file
IF TALL < HEIGHT
TALL = HEIGHT
TALLMAN = NAME
ENDIF
read next NAME, HEIGHT
ENDDO
write ‘THE TALLEST STUDENT IS’ TALLMAN, ‘WITH HEIGHT’, TALL
END
Read A, B
IF A < B
IF A < 10
X=A+B
ELSE
X=B–A
ENDIF
ELSEIF B < 5
X = A*B
ELSEIF A < 15
X = A2
ELSE
X = B2
ENDIF
write x
END