Posts

Pseudocode examples

1. Print an array 

You have an array of names called NAMES that contains 20 String values. 

Write an algorithm that will print out all the names.

loop i from 0 to 19

    output NAMES[i]

end loop

2: Print a collection

You have a collection of names called STUDENT_LIST that contains an unknown number of values. 

Write an algorithm that will print out all the student names.

loop while STUDENT_LIST.hasNext()

    output STUDENT_LIST.getNext()

end loop

3: Calculate min/max/average of an array 

You have an array of 7 integers called ARR.

Output the minimum, maximum and average value of the values in the array ARR.

SUM = 0
MAX = ARR[0]
MIN = ARR[0]
loop i from 0 to 6
    SUM = SUM + ARR[i]
    if ARR[i] > MAX then
        MAX = ARR[i]
    end if
    if ARR[i] < MIN then
        MIN = ARR[i]
    end if
end loop
AVERAGE = SUM / 7
OUTPUT MAX, MIN, AVERAGE

4: Calculate min/max/average of a collection 

You have a collection of double values called GRADES. 

Output the minimum, maximum and average value of the values in the collection.

MAX = GRADES.getNext()
MIN = MAX
SUM = 0
COUNT = 0
GRADES.resetNext()
loop while GRADES.hasNext()
    X = GRADES.getNext()
    COUNT = COUNT + 1
    SUM = SUM + X
    if X > MAX then
        MAX = X
    end if
    if X < MIN then
        MIN = X
    end if
end loop
AVERAGE = SUM / COUNT
OUTPUT MAX, MIN, AVERAGE

5: Search a value in an array 

You have a char array of 26 letters called ALPHA containing all the letters of the English alphabet. 

There are no duplicate letters. Output the location (index) of the letter ‘C’.

POSITION = -1
loop I from 0 to 25
    if ALPHA[I] = ‘C’ then
        POSITION = I
    end if
end loop
output POSITION

6: Find a value in a collection (a)

You have a list of students called STUDENT_LIST. 

Search the list for a student called “Sam”. 

Output an appropriate message.

FOUND = false

loop while STUDENT_LIST.hasNext()

X = STUDENT_LIST.getNext()

if X == ‘Sam’ then

FOUND = true

end if

end loop

if FOUND == true then

output ‘Sam was found’

else

output ‘Sam was not found’

end if

7: Find a value in a collection (b)

You have a list of students called STUDENT_LIST. 

Search the list for a student called “Tom”.

The algorithm should be as efficient as possible (i.e. the algorithm should stop searching if Tom is found; no need to search the entire collection).

Output an appropriate message.

FOUND = false

loop while STUDENT_LIST.hasNext() AND FOUND == false

X = STUDENT_LIST.getNext()

if X == ‘Tom’ then

FOUND = true

end if

end loop

if FOUND == true then

output ‘Tom was found’

else

output ‘Tom was not found’

end if