Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Chapter 8 - Pseudocode

Friday, May 17, 2024 5:19 PM

Psuedocode - A simple way to show an algorithm

= is an Arrow <- unless its in a condition

= in conditions. For variables you use <- ARRAY <- [50,60,70,80,90,100]


ARRAY2 <- [10,20,40,50,20,30]
OUTPUT/INPUT ARRAY3 <- [50,30,100,20,10,1000]

OUTPUT "Enter your name : " FUNCTION CalculateAverage(Array: ARRAY[1:6] OF INTEGER) RETURNS INTEGER
INPUT Name Total <- 0
FOR c <- 1 TO 6
Constant - A variable that doesn't change its value later on in the code Total <- Total + Array[c]
NEXT c
CONSTANT VariableName <- value // 50+60+70+80+90+100
RETURN ROUND(Total/6, 0) // 75
Types ENDFUNCTION
ArrayOneAverage <-- CalculateAverage(ARRAY) // [50,60,70,80,90,100]
STRING - A combination of different letters and numbers - Alphanumeric - "John Smith" OUTPUT ArrayOneAverage // 75
CHAR - A singular letter - 'A'
INTEGER - A whole number - 53
REAL - A number going into decimal points - 6784.23
BOOLEAN - TRUE or FALSE - TRUE

DECLARATION SYNTAX

DECLARE VariableNames(seperated by commas(,)) : Type

DECLARE Num1, Num2 : INTEGER


DECLARE Name : STRING

CONDITIONAL STATEMENTS

IF…THEN...ELSE…ENDIF

IF Condition
THEN Condition result is 1
ELSE Condition result is 0
ENDIF
0/FALSE 1/TRUE 0 /FALSE
(Num1 > Num2) OR NOT (Num2 > Num3) OR (Num4 > Num3)

CASE OF…ENDCASE

A singular variable is compared to other values

CASE OF VariableName
Value1: Statement
Value2: Statement
Value3: Statement
ENDCASE
OUTPUT "Enter num between 1-3"
INPUT Num

CASE OF Num
1: OUTPUT "Hello"
2: OUTPUT "Bye"
3: OUTPUT "You're stupid"
OTHERWISE: OUTPUT "You're too stupid"
ENDCASE

Loops

Going over a code over and over and over and over in iterations

WHILE…DO…ENDWHILE - Pre condition loop


REPEAT…UNTIL - Post condition loop
FOR…TO…NEXT - Count controlled loop

FOR VariableAssigning TO Limit


ACTION
Next VariableName

FOR c <- 0 TO 50
ACTION
NEXT c

OUTPUT "Enter a number between 1 and 50"


INPUT Num
WHILE Num < 1 OR Num > 50 DO
OUTPUT "You stupid little guy enter a number between 1 and 50"
INPUT Num

New Section 1 Page 1


INPUT Num
ENDWHILE

REPEAT
OUTPUT "Enter a number between 1 and 50"
INPUT Num
UNTIL Num < 1 OR Num > 50

1 - 50

// 49

Num < 1 OR Num > 50 // 0


Num >= 1 AND Num <=50 // 1

Totalling, Counting, Max Min Avg.

A Teacher is inputting the records of 50 students. Total all records and


output them. Use a FOR loop

Total = 0
for count in range(1,50):
record = int(input('Input student record for student : '))
Total = Total + record
print(Total)

DECLARE Total, Record : INTEGER


FOR Count <- 1 TO 50
INPUT Record
Total <- Total + Record
NEXT Count
OUTPUT Total

Counting

A teacher inputs 50 students marks. Count how many of them passed. Passed = above
50. Use a FOR loop

Passed = 0
for count in range(1,50):
marks = int(input('Enter student marks : '))
if(marks > 50):
Passed = Passed + 1

DECLARE Passed, Marks : INTEGER


Passed <- 0
FOR Count <- 1 TO 50
INPUT Marks
IF Marks > 50
THEN Passed <- Passed + 1
ENDIF
NEXT Count
OUTPUT Passed

Minimum, Maximum, Average

A teacher inputs 5 students marks. The maximum achievable is 100. Minimum is 0.


Calculate highest, lowest, and average.

Highest = 0
Lowest = 100
Total = 0
for count in range(0,5):
mark = int(input('Enter mark : '))
if(mark > Highest):
Highest = mark
if(mark < Lowest):
Lowest = mark
Total = Total + mark
avg = Total/5
print(Highest, Lowest, avg)
'''
Test Data = 40, 70, 10, 5, 90
Lowest - 40 , Highest - 40
Lowest - 40 , Highest - 70
Lowest - 10 , Highest - 70

New Section 1 Page 2


Lowest - 10 , Highest - 70
Lowest - 5 , Highest - 70
Lowest - 5 , Highest - 90
Output - 90, 5, 43.0
'''

DECLARE Highest, Lowest, Average, Mark, Total : INTEGER


Total <- 0
Highest <- 0
Lowest <- 100
FOR student <- 1 TO 5
INPUT Mark
IF Mark > Highest
THEN Highest <- Mark
ENDIF
IF Mark < Lowest
THEN Lowest <- Mark
ENDIF
Total <- Total + Mark
NEXT student
Average <- Total/5
OUTPUT Highest
OUTPUT Lowest
OUTPUT Average

Functions & Procedures

You're the teacher at a school. Your task is to add all student's marks and figure out the grade.

Function is used to run a module and return a value as the answer

FUNCTION FunctionName(Parameters(seperated by commas)) RETURNS ReturnType


FunctionActions
RETURN Val
ENDFUNCTION

FUNCTION AddMarks(MathMarks: INTEGER, EnglishMarks: INTEGER, PhysicsMarks: INTEGER,


ComputerMarks: INTEGER, ChemistryMarks: INTEGER) RETURNS INTEGER
// 10, 10, 10, 9, 10
TotalMarks <-- 0
TotalMarks <-- MathMarks + TotalMarks // 10
TotalMarks <-- EnglishMarks + TotalMarks // 20
TotalMarks <-- ChemistryMarks + TotalMarks // 30
TotalMarks <-- ComputerMarks + TotalMarks // 39
TotalMarks <-- PhysicsMarks+ TotalMarks // 49
RETURN TotalMarks // 49
ENDFUNCTION

TotalMarksOfStudent <-- AddMarks(10, 10, 10, 9, 10)

Procedures

DO NOT return a value

PROCEDURE ProcedureName(Parameters)
ProcedureWork
ENDPROCEDURE

SendStars(5)
*****

PROCEDURE SendStars(Stars: INTEGER)


FOR c <-- 1 TO Stars
OUTPUT "*"
NEXT
ENDPROCEDURE

Arrays

Just a collection of different variables of the same data type.


An array is identified by []
Inside of an array each value is seperated by a comma (,)

[10, 20, 30, 40, 50] - 1D Array

DECLARE array: ARRAY[1:5] OF INTEGER


array <-- [1,2,3,4,5]

1 2 3 4 5

DECLARE arrayName: ARRAY[NoOfRows:NoOfColumns] OF DataType

DECLARE People: ARRAY[1:3] OF STRING

People <- ["John", "Sam", "Albughdad ul Shawarma"]

New Section 1 Page 3


People <- ["John", "Sam", "Albughdad ul Shawarma"]

DECLARE Array: ARRAY[1:5, 1:6] OF INTEGER

Array <- [[10,20,30,40,50, 6],[60,70,80,90,100, 6],[10,40,20,23,21, 6],[9,4,2,2,1, 6],[21,23,21,32,33, 6]]

An array AccDetails[] is a 2D Array with 50 clients information. And each client has their balance,
withdrawal balance & debt balance inside.

DECLARE AccDetails: ARRAY[1:50, 1:3] OF INTEGER

DECLARE CoolArray: ARRAY[1:3, 1:5] OF INTEGER

1 1 1
1 1 1
1 1 1
1 1 1
1 1 1

Routine Syntax Routine Description Routine Example with Output


MOD(ValueUsedToDivide, Returns the Remainder of the division MOD(4,2)
ValueDividedBy) 4 MOD 2 in PSEUDOCODE

Popular Case : Even number divided by 2


will return 0
DIV(ValueUsedToDivide, Returns the Quotiant of the division DIV(10,3)
ValueDividedBy) 10 DIV 3 in PSEUDOCODE

ROUND(Number, DecimalPoints) Rounds the number to the amount of d.p specified ROUND(6.7382, 2) -> 6.74
RANDOM() Returns a random number B/W 1 and 0 Inclusive RANDOM() -> 1 or 0
LEFT(string, Returns the string from the left to the amount of LEFT("Ateeb Sohail", 5) -> "Ateeb"
amountOfCharactersToLeft) character specified
RIGHT(string, Returns the string from the right to the amount of RIGHT("Ateeb Sohail", 6) -> "Sohail"
amountOfCharactersToRight) character specified
MID(String, Position, Returns the string from the position it started at MID("Ateeb Sohail", 3, 5) -> "eeb S"
AmountOfCharacters)
LENGTH(String) Returns the length of the string LENGTH("Ateeb Sohail") -> 12
UCASE(String) Returns string in upper case UCASE("Ateeb Sohail") -> ATEEB SOHAIL
LCASE(String) Returns string in lower case LCASE("Ateeb Sohail") -> ateeb sohail

Linear Search

Used to find a value in an array using a FOR loop usually(unless mentioned otherwose)

DECLARE Array: ARRAY[1:5] OF STRING

Find 'Rick' in the Array. Return the position of Rick, if not found return -1. Create it in a function named
Find with 2 parameters, the array below and the findvalue variable below
Array <- ["Ateeb", "Rick", "Brittany", "Megatron", "Sam"]
FindValue <- "Rick"

FUNCTION Find(Array: ARRAY[1:5] OF STRING, FindValue: STRING) RETURNS INTEGER


Index <- -1
FOR c <- 1 TO 5
IF Array[c] = FindValue
THEN Index <- c
ENDIF
NEXT c
RETURN Index
ENDFUNCTION

PositionOfRick <- Find(Array, "Rick")

Bubble Sort

DECLARE Numbers: ARRAY[1:3] OF INTEGER


Numbers <- [3,2,1]

REPEAT
Swap <- FALSE
FOR Index <- 1 TO 3
IF Numbers[Index] > Number[Index+1]
THEN
Temp <- Numbers[Index]
Numbers[Index] <- Number[Index +1]
Number[Index+1] <- Temp

New Section 1 Page 4


Number[Index+1] <- Temp
Swap <- TRUE
ENDIF
NEXT Index
UNTIL Swap = FALSE

Swap Index Temp Numbers


FALSE [3,2,1]
TRUE 1 3 [2,3,1]
2 3 [2,1,3]
FALSE
TRUE 1 2 [1,2,3]
2 [1,2,3]
FALSE

Range Check - It's used to check whether or not a certain number is within a range, e.g 50-100.
Length Check - It's used to check the length of a string
Type Check - It's used to check the data type of a variable
Presence Check - It's used to check if anything has been input
Format Checks - It's used to check the format of a string or verify it starts with something
Check Digits - It's used mainly in ISBN-13 or Modulo-11

Range Check

Question : Input a number and verify its between 1 through 10 inclusive. You do not
Need to reinput the number

INPUT Number
IF Number < 1 OR Number > 10
THEN OUTPUT "Number isn't within range"
ENDIF

Length Check

Library Routine - LENGTH(String)

Question : Input a string and verify that it is 8 characters long. You do not need to reinput.

INPUT String
IF LENGTH(String) <> 8
THEN OUTPUT "Length is not 8"
ENDIF

Type Check

Question : Input a number and check if it’s a whole number


DIV(Number)

INPUT Number
IF Number <> DIV(Number, 1)
THEN OUTPUT "Enter Whole Number"
ENDIF

Presence Check

Question : Input a string and verify it isnt empty

INPUT String
IF String = ""
THEN OUTPUT "Empty"
ENDIF

Format Check

LEFT, RIGHT, MID

PK844
PKNNN

LEFT 2 CHARACTERS ARE PK

Question : Input a string and check if it follows the format "PKNNN"

INPUT String
IF LEFT(String, 2) <> "PK"
THEN OUTPUT "Invalid Format"
ENDIF

Question : Input a string and check if it follows the format "NNNPK"

INPUT String [10]

New Section 1 Page 5


THEN OUTPUT "Invalid Format"
ENDIF

Question : Input a string and check if it follows the format "NNNPK"

INPUT String [10]


IF RIGHT(String, 2) <> "PK"
THEN OUTPUT "Invalid Format"
ENDIF

REMEMBER TO LEARN DIFF BETWEEN VERIF AND VALID

// Initializing all variables to their default values or for lowest we're initializing to the highest
possible.

NoOfDays <-- 5
TotalClassMinutes <- 0
Lowest <-- 1000
LowestIndex <- 0
// Starting a for loop to the class size
FOR Student <- 1 TO ClassSize
// Initializing the default values for total screen time and number of 300 greaters for
each student
TotalScreenTime <- 0
NumberOf300Greaters <- 0
// Starting a for loop till the number of days
FOR Day <- 1 TO NoOfDays
// Inputting screen time for a certain number of day
OUTPUT "Enter Amount of screentime for day ", Day
INPUT ScreenTime
// Adding screen time to total
Total <- ScreenTime + Total
// Adding screen time to total class screen time
TotalClassMinutes <-- ScreenTime + TotalClassMinutes
// Adding the screentime to the ScreenTime array
ScreenTime[Student, Day] <-- ScreenTIme
// Calculating amount of 300 greaters
IF ScreenTime > 300
THEN Number300Greaters <- Number300Greaters + 1
ENDIF
NEXT Day
// Checking if total screen time is less than the lowest recorded
IF(TotalScreenTime < Lowest)
THEN
// If total screen time is less adding the screen time to the lowest and
storing indedx
Lowest <-- TotalScreenTIme
LowestIndex <-- Student
ENDIF
// Outputting the name, no of hours, minutes and days with more than 300 minutes
OUTPUT "Name of student : ", StudentName[Student]
OUTPUT "No of hours : ", DIV(TotalScreenTime, 60), "No of Minutes : ",
MOD(TotalScreenTime, 60)
OUTPUT "Number of days with more than 300 : ", NumberOf300Greaters
NEXT Student
// Calculatng total class average
Average <- TotalClassMinutes / NoOfDays
// Outputting total class average and lowest student name
OUTPUT "Class Average : ", Average
OUTPUT "Lowest Student Name : ", StudentName[LowestIndex]
StudentName - Size ClassSize - ["Ateeb", "Rick", "Megatro]
StudentMark - Size ClassSize - [[50, 100], [40, 20], [5, 10]]
SubjectSize

DECLARE Distinctions, Merits, Passes, Fails, TotalStudentMark, Average : INTEGER

New Section 1 Page 6


DECLARE Distinctions, Merits, Passes, Fails, TotalStudentMark, Average : INTEGER
DECLARE Grade : STRING

Distinctions <- 0
Merits <- 0
Passes <- 0
Fails <- 0
FOR Student <- 1 TO ClassSize
TotalStudentMark <- 0
FOR Subject <- 1 TO SubjectNo
TotalStudentMark <- TotalStudentMark + StudentMark[Student,Subject]
NEXT Subject
Average = ROUND(TotalStudentMark/SubjectNo, 0)
IF Average >= 70
THEN Grade <- "distinction"
Distinctions <- Distinctions + 1
ENDIF
IF Average >= 55 AND Average < 70
THEN Grade <- "merit"
Merits <- Merits + 1
ENDIF
IF Average >= 40 AND Average < 55
THEN Grade <- "pass"
Passes <- Passes + 1
ENDIF
If Average < 40
THEN Grade <- "fail"
Fails <- Fails + 1
ENDIF
OUTPUT "Student Name : ", StudentName[Student]
OUTPUT "Student Mark Total : ", TotalStudentMark
OUTPUT "Student Average Marks : ", Average
OUTPUT "Student Grade : ", Grade
NEXT Student

OUTPUT "No. of distinctions : ", Distinctions


OUTPUT "No. of Merits : ", Merits
OUTPUT "No. of Passes : ", Passes
OUTPUT "No. of Fails : ", Fails

WoodType[1] <- "Laminate"


WoodType[2] <- "Pine"
WoodType[3] <- "Oak"
Price[1] <- 29.99
Price[2] <- 39.99
Price[3] <- 54.99

Flag <- FALSE


CurrentCustomer <- 1
WHILE Flag = FALSE
INPUT CustName
INPUT CustomRoomLength
WHILE CustRoomLength < 1.5 OR CustRoomLength > 10
DO
OUTPUT "Invalid Customer Room Length. Make sure it's between 1.5 and 10.0 inclusive
Re-enter : "
INPUT CustRoomLength
ENDWHILE
INPUT CustRoomWidth
WHILE CustRoomWidth < 1.5 OR CustRoomWidth > 10
DO
OUTPUT "Invalid Customer Room Width. Make sure it's between 1.5 and 10.0 inclusive.
Re-enter : "
INPUT CustRoomWidth
ENDWHILE
RoomArea <- CustRoomLength * CustRoomWidth
OUTPUT "Enter your wood choice"
FOR c <- 1 TO 3
OUTPUT c, WoodType[c], Price[c]
Next c
OUTPUT "Enter a number between 1 and 3"
TempFlag <- FALSE
REPEAT
INPUT WoodChoice
IF WoodChoice <1 OR WoodChoice > 3
THEN
OUTPUT "Reenter and choose 1-3 : "
INPUT WoodChoice
ELSE
TempFlag <- TRUE
ENDIF
UNTIL TempFlag = TRUE
PriceOfWood <- RoomArea * Price[WoodChoice]

New Section 1 Page 7


PriceOfWood <- RoomArea * Price[WoodChoice]
Quotations[CurrentCustomer, 1] <- ROUND(CustRoomLength, 1)
Quotations[CurrentCustomer, 2] <- ROUND(CustRoomWidth, 1)
Quotations[CurrentCustomer, 3] <- ROUND(RoomArea + 0.5, 0)
Quotations[CurrentCustomer, 4] <- WoodChoice
Quotations[CurrentCustomer, 5] <- ROUND(PriceOfWood, 2)
OUTPUT "Customer Name : ", Customers[CurrentCustomer]
OUTPUT "Wood Choice : ", WoodType[WoodChoice]
OUTPUT "Total Price : ", PriceOfWood
CurrentCustomer <- CurrentCustomer + 1
IF CurrentCustomer > 100
THEN Flag <- TRUE
ENDIF
ENDWHILE

New Section 1 Page 8


][][
Saturday, May 18, 2024 9:16 PM

New Section 1 Page 9

You might also like