0% found this document useful (0 votes)
4 views

8-PseudocodePython

Chapter 8 covers pseudocode as a method for illustrating algorithms, detailing variable types, conditional statements, loops, functions, and procedures. It provides examples of how to declare variables, implement loops for counting and averaging, and manage arrays. The chapter also discusses validation checks and sorting algorithms, emphasizing the importance of structure in programming logic.

Uploaded by

ash.kwok2208
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

8-PseudocodePython

Chapter 8 covers pseudocode as a method for illustrating algorithms, detailing variable types, conditional statements, loops, functions, and procedures. It provides examples of how to declare variables, implement loops for counting and averaging, and manage arrays. The chapter also discusses validation checks and sorting algorithms, emphasizing the importance of structure in programming logic.

Uploaded by

ash.kwok2208
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

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 <- 1 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
ENDWHILE

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

1 - 50

New Section 1 Page 1


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


Total <- 0
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
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

New Section 1 Page 2


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

ArrayName[Index]

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

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

ArrayName[1,

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

New Section 1 Page 3


1 1 1

Routine Syntax Routine Description Routine Example with Output


ValueUsedToDivide MOD Returns the Remainder of the division % in python
ValueDividedBy 4 MOD 2 in PSEUDOCODE

Popular Case : Even number divided by 2


will return 0
ValueUsedToDivide DIV Returns the Quotiant of the division 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 2
IF Numbers[Index] > Number[Index+1]
THEN
Temp <- Numbers[Index]
Numbers[Index] <- Number[Index +1]
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

New Section 1 Page 4


Need to reinput the number

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

REPEAT
OUTPUT "Enter Number between 1 and 10 :"
INPUT Number
UNTIL Number >= 1 AND Number <= 10

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

REPEAT
OUTPUT "Enter string of length 8 :"
INPUT String
UNTIL LENGTH(String) = 8

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

REPEAT
OUTPUT "Enter a whole number : "
INPUT Number
UNTIL Number = DIV(Number, 1)

Presence Check

Question : Input a string and verify it isnt empty

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

REPEAT
OUTPUT "Enter a non-empty string : "
INPUT String
UNTIL String <> "" [10]

Format Check

LEFT, RIGHT, MID

PK844
PKNNN
// Initializing all variables to their default values or for lowest we're initializing to the highest
LEFT 2 CHARACTERS ARE PK possible.

Question : Input a string and check if it follows the format "PKNNN" NoOfDays <-- 5
TotalClassMinutes <- 0
INPUT String Lowest <-- 1000
IF LEFT(String, 2) <> "PK" LowestIndex <- 0
THEN OUTPUT "Invalid Format" // Starting a for loop to the class size
ENDIF FOR Student <- 1 TO ClassSize
// Initializing the default values for total screen time and number of 300 greaters for
REPEAT each student
OUTPUT "Enter a string in format PKNNN" TotalScreenTime <- 0
INPUT String NumberOf300Greaters <- 0
UNTIL LEFT(String, 2) = "PK" // Starting a for loop till the number of days
FOR Day <- 1 TO NoOfDays
Question : Input a string and check if it follows the format "NNNPK" // Inputting screen time for a certain number of day
OUTPUT "Enter Amount of screentime for day ", Day
INPUT String INPUT ScreenTime
IF RIGHT(String, 2) <> "PK" // Adding screen time to total
THEN OUTPUT "Invalid Format" Total <- ScreenTime + Total
ENDIF // Adding screen time to total class screen time
TotalClassMinutes <-- ScreenTime + TotalClassMinutes
REPEAT // Adding the screentime to the ScreenTime array
OUTPUT "Enter a string following pattern NNNPK" ScreenTime[Student, Day] <-- ScreenTIme
INPUT String // Calculating amount of 300 greaters
UNTIL RIGHT(String, 2) = "PK" IF ScreenTime > 300
THEN Number300Greaters <- Number300Greaters + 1
REMEMBER TO LEARN DIFF BETWEEN VERIF AND VALID ENDIF
NEXT Day
// Checking if total screen time is less than the lowest recorded
IF(TotalScreenTime < Lowest)

New Section 1 Page 5


UNTIL RIGHT(String, 2) = "PK" IF ScreenTime > 300
THEN Number300Greaters <- Number300Greaters + 1
REMEMBER TO LEARN DIFF BETWEEN VERIF AND VALID 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


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

New Section 1 Page 6


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
File handling
ELSE
TempFlag <- TRUE
FileName <- "Myfile.txt"
ENDIF
UNTIL TempFlag = TRUE
OPEN FileName FOR WRITE
PriceOfWood <- RoomArea * Price[WoodChoice]
OUTPUT "Enter a line"
Quotations[CurrentCustomer, 1] <- ROUND(CustRoomLength, 1)
INPUT TextLine
Quotations[CurrentCustomer, 2] <- ROUND(CustRoomWidth, 1)
WRITEFILE, TextLine
Quotations[CurrentCustomer, 3] <- ROUND(RoomArea + 0.5, 0)
CLOSEFILE(FileName)
Quotations[CurrentCustomer, 4] <- WoodChoice
Quotations[CurrentCustomer, 5] <- ROUND(PriceOfWood, 2)
OUTPUT "File Contains this line of text : "
OUTPUT "Customer Name : ", Customers[CurrentCustomer]
OPEN FileName FOR READ
OUTPUT "Wood Choice : ", WoodType[WoodChoice]
READFILE, TextLine
OUTPUT "Total Price : ", PriceOfWood
OUTPUT TextLine
CurrentCustomer <- CurrentCustomer + 1
CLOSEFILE(Filename)
IF CurrentCustomer > 100
THEN Flag <- TRUE
OPEN
ENDIF
CLOSEFILE
ENDWHILE
WRITEFILE
READFILE

READ
WRITE

OPEN Filename/filepath FOR operation

CLOSEFILE(Filename/filepath)

File = open(filename, "w")


Textline = input("Enter line ")
File.write(TextLine)
File.close()

File = open(filename, "r")


TextLine = File.read()
Print(TextLine)
File.close()

New Section 1 Page 7

You might also like