Pseudocode
Pseudocode
Reserved and Optional Words
General Structure
General Structure
QuickSort(A, first, last)
Input: Array of integers A, integers first and last to mark beginning and end of the array
Output: Sorted integer array A
Statement 1
Statement 2
…
Variables
Statements
Simple statements
Function calls
Conditions
IF (expression) THEN
Statements…
ELSIF (expression) THEN
Statements…
ELSE
Statements
ENDIF
Conditions - example
IF (a=1) THEN
a←a*2
ELSEIF (a=2) THEN
a←a*3
B←a+5
ELSE
a←a*a*a;
ENDIF
Roots of a quadratic function
Read a, b, c from terminal
d←b*b - 4*a*c
IF (d<0) THEN
Write “no roots”
ELSIF (d=0) THEN
r1← -b / (2*a)
Write “Root: ”, r1
ELSE
r1←(-b + sqrt(d)) / (2*a)
r2←(-b - sqrt(d)) / (2*a)
Write “Roots: ”, r1, r2
ENDIF
Logical Operators
IF (a=1 AND b=2) THEN
…
IF (a=1 OR c>=5) THEN
…
Invalid expressions
CASE statement
CASE (expression) IS
Const1:
Statements…
Const2:
Statements…
…
DEFAULT:
Default behaviour statements…
ENDCASE
CASE example
Read option from keyboard
CASE (option) IS
‘a’:
Read num from keyboard
value←value+num
‘b’:
value←0;
‘c’:
value←10000;
DEFAULT:
Write “Invalid option” to the screen
ENDCASE
FOR loops
FOR variable IS start TO end STEP inc DO
Statements…
ENDFOR
for (variable = start; variable <= end, variable=variable+inc){
Statements…
}
FOR loop example
sum←0
FOR i = 0 TO N-1 DO
sum←sum+array[i]
ENDFOR
average←sum/N
Write “Average is:”, average
WHILE loops
WHILE (expression) DO
Statement 1
Statement 2
..
ENDWHILE
WHILE example
n←0
WHILE (n < 100) DO
Write “N: ”, n
n←n+1
ENDWHILE
REPEAT loops
REPEAT
Statement 1
Statement 2
Statement 3
…
UNTIL (expression)
REPEAT example
REPEAT
Display menu on the screen
Read user choice as x
UNTIL (x = ‘e’)
Quicksort
Quicksort (A,p,r)
IF (p < r) THEN
q ← Partition(A,p,r)
Quicksort (A,p,q)
Quicksort (A,q+1,r)
ENDIF
Quicksort/Partition
Partition (A,p,r)
pivot ← A[p]
i = p - 1
FOR j = p TO r - 1
IF A[j] < pivot
i ← i + 1
swap A[i] and A[j]
ENDIF
ENDFOR
swap A[i + 1] and A[p]
RETURN i + 1