Ix p2 Final Term Handout 3
Ix p2 Final Term Handout 3
FOR i ← 0 TO 4
DISPLAY "Enter marks for student: "
INPUT result
marks[i] ← result
NEXT i
1.2. User-Defined Length: First, ask the user how many values they want to enter, then
take input accordingly.
i ← 0
REPEAT
OUTPUT "Enter marks for student:"
INPUT result
marks[i] ← result
i ← i + 1
UNTIL i = n
* same algorithm using FOR loop
FOR i ← 0 TO n-1
OUTPUT "Enter marks for student: "
INPUT result
marks[i] ← result
NEXT i
1.3. Input Until Sentinel Value: Keep taking input until the user enters -1.
1
DECLARE marks: Array OF INTEGER
i ← 0
REPEAT
OUTPUT "Enter marks for student (enter -1 to stop): "
INPUT result
total ← 0
FOR i ← 0 TO 4
total ← total + marks[i]
NEXT i
average ← total / 5
OUTPUT "Total Marks: ", total
OUTPUT "Average Marks: ", average
2.2. Count
count ← 0
FOR i ← 0 TO 4
IF marks[i] >= 90 THEN
count ← count + 1
END IF
NEXT i
2
2.3. Min, max
MinMark ← marks[0]
MaxMark ← marks[0]
FOR i ← 0 TO 4
IF marks[i] < MinMark THEN
MinMark ← marks[i]
ENDIF
searchNum ← 20
found ← false
FOR i ← 0 TO 6
IF marks[i] = searchNum THEN
found ← true
ENDIF
NEXT i
Example 2 : Write an algorithm to find the name “Don” from the given array names.
names = [“Jamal”, “Kamal”, “Rahim”, “Don”]
searchName ← “Don”
found ← false
FOR i ← 0 TO 3
IF names[i] = searchName THEN
found ← true
ENDIF
NEXT i
3
* The pseudocode line ( IF found THEN ) is the short form of ( IF found = true THEN )
both are correct.
Note: sorted array after running the algorithm should be [9, 10, 15, 17, 18, 19, 20]
REPEAT
Swap = false
FOR i ← 0 TO 5
IF marks[i] > marks[i+1] THEN
Swap = true
temp ← marks[i]
marks[i] ← marks[i+1]
marks[i+1] ← temp
ENDIF
NEXT i
UNTIL Swap = false
REPEAT
Swap = false
FOR i ← First TO Last -1
IF marks[i] > marks[i+1] THEN
Swap = true
temp ← marks[i]
marks[i] ← marks[i+1]
marks[i+1] ← temp
ENDIF
NEXT i
Last ← Last - 1
UNTIL Swap = false OR Last = 1
* The pseudocode line ( UNTIL Swap OR Last = 1) is the short form ( UNTIL Swap =
false OR Last = 1) both are correct.