Python → Cambridge IGCSE Pseudocode
Cambridge IGCSE / O Level 0478 · 2210
Key rules
- 01Every variable is declared first with a type:
DECLARE Total : INTEGER. Names are written in PascalCase. - 02Arrays are declared
ARRAY[0:n] OF typewith a lower bound of 0, so Python/Java indexes are kept unchanged. - 03
IF … THEN … ELSE … ENDIFwith THEN and ELSE on their own lines. - 04
FOR I ← A TO B … NEXT Iincludes the end value B;WHILE … DO … ENDWHILE. - 05Integer division and remainder are functions:
DIV(a, b)andMOD(a, b); substrings useSUBSTRING(s, start, length).
Contents10 sections
Quick reference
| Concept | Python | IGCSE |
|---|---|---|
| Assignment | x = 5 | DECLARE X : INTEGERX ← 5 |
| Output | print("Hi") | OUTPUT "Hi" |
| Input | name = input() | DECLARE Name : STRINGINPUT Name |
| If | if x > 3: print(x) | IF X > 3 THEN OUTPUT XENDIF |
| Else if | if x > 3: print(1)elif x > 1: print(2) | IF X > 3 THEN OUTPUT 1 ELSE IF X > 1 THEN OUTPUT 2 ENDIFENDIF |
| While loop | while x < 3: x = x + 1 | WHILE X < 3 DO X ← X + 1ENDWHILE |
| Counting loop | for i in range(5): print(i) | DECLARE I : INTEGERFOR I ← 0 TO 4 OUTPUT INEXT I |
| Repeat n times | for i in range(3): print("Hi") | DECLARE I : INTEGERFOR I ← 0 TO 2 OUTPUT "Hi"NEXT I |
| For each | for x in xs: print(x) | FOR I ← 0 TO 1 X ← Xs[I] OUTPUT XNEXT I |
| Create array | xs = [4, 7, 9] | DECLARE Xs : ARRAY[0:2] OF INTEGERXs[0] ← 4Xs[1] ← 7Xs[2] ← 9 |
| Array access | print(xs[0]) | OUTPUT Xs[0] |
| Length | print(len(xs)) | OUTPUT 3 |
| Function + return | def twice(n): return n * 2print(twice(4)) | FUNCTION Twice(N : INTEGER) RETURNS INTEGER RETURN N * 2ENDFUNCTIONOUTPUT Twice(4) |
| Procedure + call | def show(n): print(n)show(3) | PROCEDURE Show(N : INTEGER) OUTPUT NENDPROCEDURECALL Show(3) |
| Integer division | b = a // 2 | B ← DIV(A, 2) |
| Remainder | b = a % 2 | B ← MOD(A, 2) |
| Not equal | print(a != 2) | OUTPUT A <> 2 |
| And / or / not | print(a and not b or b) | OUTPUT A AND NOT B OR B |
| String join | t = s + "cd" | T ← s + "cd"No equivalent |
| Random 1–6 | r = random.randint(1, 6) | R ← ROUND(RANDOM() * 5, 0) + 1 |
01Basics
Cambridge pseudocode is strongly typed: each variable is declared once at the top with DECLARE Name : TYPE before it is used. The converter works out the type (INTEGER, REAL, STRING, BOOLEAN) from your code and writes names in PascalCase.
Examples8
1.1
Comment
Comments start with // in every standard. Write them before the line they explain.
# Calculate the area of a rectanglearea = 4 * 3DECLARE Area : INTEGER// Calculate the area of a rectangleArea ← 4 * 31.2
Assign a variable
Cambridge uses ← for assignment and declares the variable with its type first.
score = 0score = score + 10DECLARE Score : INTEGERScore ← 0Score ← Score + 101.3
Variables of different types
The four basic Cambridge types are INTEGER, REAL, STRING and BOOLEAN. Boolean values are written TRUE / FALSE.
count = 5price = 2.75name = "Ana"found = FalseDECLARE Count : INTEGERDECLARE Price : REALDECLARE Name : STRINGDECLARE Found : BOOLEANCount ← 5Price ← 2.75Name ← "Ana"Found ← FALSE1.4
Constant
Cambridge has a real CONSTANT Name ← value statement. A name in capitals (or Java final) becomes a CONSTANT.
MAX_SIZE = 50print(MAX_SIZE)CONSTANT MaxSize ← 50OUTPUT MaxSizetotal = 42print(total)DECLARE Total : INTEGERTotal ← 42OUTPUT Total1.6
Output text and a value
OUTPUT takes a comma-separated list, so text and values are separated by commas.
age = 16print("Age:", age)DECLARE Age : INTEGERAge ← 16OUTPUT "Age:", Age1.7
Input text
A prompt becomes its own OUTPUT line, followed by INPUT Name. The variable still needs a DECLARE.
name = input("Enter your name: ")print("Hello " + name)DECLARE Name : STRINGOUTPUT "Enter your name: "INPUT NameOUTPUT "Hello ", Name1.8
Input a number
int() (or sc.nextInt()) is not written, but it tells the converter to DECLARE the variable as INTEGER.
age = int(input("Enter your age: "))print(age + 1)DECLARE Age : INTEGEROUTPUT "Enter your age: "INPUT AgeOUTPUT Age + 1Exercises1
Q1.Ask for the user's name and favourite number, then print a message with both.
name = input("Name: ")number = int(input("Favourite number: "))print(name, number)Show answerHide answer
DECLARE Name : STRINGDECLARE Number : INTEGEROUTPUT "Name: "INPUT NameOUTPUT "Favourite number: "INPUT NumberOUTPUT Name, Number02Operators
IGCSE writes integer division and remainder as functions: DIV(a, b) and MOD(a, b). Not-equal is <> and powers use ^.
Examples7
2.1
Arithmetic
+ - * / are the same in every standard. / always gives a real (decimal) result.
a = 7b = 2print(a + b)print(a - b)print(a * b)print(a / b)DECLARE A : INTEGERDECLARE B : INTEGERA ← 7B ← 2OUTPUT A + BOUTPUT A - BOUTPUT A * BOUTPUT A / B2.2
Integer division
Integer division is the function DIV(a, b). Java / between two ints is also integer division.
minutes = 135hours = minutes // 60print(hours)DECLARE Minutes : INTEGERDECLARE Hours : INTEGERMinutes ← 135Hours ← DIV(Minutes, 60)OUTPUT Hoursn = 17if n % 2 == 0: print("even")else: print("odd")DECLARE N : INTEGERN ← 17IF MOD(N, 2) = 0 THEN OUTPUT "even" ELSE OUTPUT "odd"ENDIFside = 5area = side ** 2print(area)DECLARE Side : INTEGERDECLARE Area : INTEGERSide ← 5Area ← Side ^ 2OUTPUT Areax = 4y = 9print(x == y)print(x != y)print(x <= y)print(x >= y)DECLARE X : INTEGERDECLARE Y : INTEGERX ← 4Y ← 9OUTPUT X = YOUTPUT X <> YOUTPUT X <= YOUTPUT X >= Y2.6
Logical and / or / not
Java &&, ||, ! and Python and, or, not all become the capitalised words AND, OR, NOT.
age = 15member = Trueif age >= 12 and age <= 18: print("teen")if age < 5 or age > 65: print("free entry")if not member: print("please register")DECLARE Age : INTEGERDECLARE Member : BOOLEANAge ← 15Member ← TRUEIF Age >= 12 AND Age <= 18 THEN OUTPUT "teen"ENDIFIF Age < 5 OR Age > 65 THEN OUTPUT "free entry"ENDIFIF NOT Member THEN OUTPUT "please register"ENDIF2.7
Joining strings
IGCSE has no joining operator for assignments (only commas in OUTPUT), so the expression is copied and flagged.
first = "Ada"last = "Lovelace"full = first + " " + lastprint(full)DECLARE First : STRINGDECLARE Last : STRINGDECLARE Full : STRINGFirst ← "Ada"Last ← "Lovelace"Full ← first + " " + lastOUTPUT Full- Not directly available in IGCSE: String concatenation could not be converted to Cambridge pseudocode. It was copied unchanged.
Exercises1
Q1.Convert a number of seconds into minutes and remaining seconds.
seconds = 200minutes = seconds // 60rest = seconds % 60print(minutes)print(rest)Show answerHide answer
DECLARE Seconds : INTEGERDECLARE Minutes : INTEGERDECLARE Rest : INTEGERSeconds ← 200Minutes ← DIV(Seconds, 60)Rest ← MOD(Seconds, 60)OUTPUT MinutesOUTPUT Rest03Selection
IGCSE writes IF condition, then THEN and ELSE indented on their own lines, and closes with ENDIF. There is no ELSEIF, so an elif chain becomes nested IFs.
Examples5
temp = 31if temp > 30: print("hot")DECLARE Temp : INTEGERTemp ← 31IF Temp > 30 THEN OUTPUT "hot"ENDIF3.2
If … else
The else branch runs when the condition is false. Only one of the two branches runs.
mark = 64if mark >= 50: print("pass")else: print("fail")DECLARE Mark : INTEGERMark ← 64IF Mark >= 50 THEN OUTPUT "pass" ELSE OUTPUT "fail"ENDIF3.3
Else-if chain
There is no else-if keyword, so each extra branch is nested inside the ELSE of the one before. Check the order of the tests: the first true branch wins.
mark = 72if mark >= 80: grade = "A"elif mark >= 70: grade = "B"elif mark >= 60: grade = "C"else: grade = "U"print(grade)DECLARE Mark : INTEGERDECLARE Grade : STRINGMark ← 72IF Mark >= 80 THEN Grade ← "A" ELSE IF Mark >= 70 THEN Grade ← "B" ELSE IF Mark >= 60 THEN Grade ← "C" ELSE Grade ← "U" ENDIF ENDIFENDIFOUTPUT Grade3.4
Nested if
An if inside another if. Indentation shows which ELSE belongs to which IF.
age = 17hasTicket = Trueif hasTicket: if age >= 18: print("enter") else: print("adult needed")else: print("buy a ticket")DECLARE Age : INTEGERDECLARE HasTicket : BOOLEANAge ← 17HasTicket ← TRUEIF HasTicket THEN IF Age >= 18 THEN OUTPUT "enter" ELSE OUTPUT "adult needed" ENDIF ELSE OUTPUT "buy a ticket"ENDIFExercises1
Q1.Print "freezing" below 0, "cold" below 15 and "warm" otherwise.
temp = int(input("Temperature: "))if temp < 0: print("freezing")elif temp < 15: print("cold")else: print("warm")Show answerHide answer
DECLARE Temp : INTEGEROUTPUT "Temperature: "INPUT TempIF Temp < 0 THEN OUTPUT "freezing" ELSE IF Temp < 15 THEN OUTPUT "cold" ELSE OUTPUT "warm" ENDIFENDIF04Loops
IGCSE has FOR I ← A TO B STEP S … NEXT I, WHILE … DO … ENDWHILE and REPEAT … UNTIL. A FOR loop includes its end value, so range(n) becomes 0 TO N - 1.
Examples8
4.1
Count from 0 to n − 1
range(n) stops before n, but a Cambridge FOR includes its end value, so the end becomes N - 1.
n = 5for i in range(n): print(i)DECLARE N : INTEGERDECLARE I : INTEGERN ← 5FOR I ← 0 TO N - 1 OUTPUT INEXT I4.2
Count with a step
STEP sets the increase. The end is the last value that can be reached (19 here, the loop shows 0, 5, 10, 15).
for i in range(0, 20, 5): print(i)DECLARE I : INTEGERFOR I ← 0 TO 19 STEP 5 OUTPUT INEXT I4.3
Count down
A negative STEP counts down. range(10, 0, -1) stops before 0, so the end value is 1.
for i in range(10, 0, -1): print(i)print("Lift off")DECLARE I : INTEGERFOR I ← 10 TO 1 STEP -1 OUTPUT INEXT IOUTPUT "Lift off"balance = 100years = 0while balance < 200: balance = balance * 1.1 years = years + 1print(years)DECLARE Balance : REALDECLARE Years : INTEGERBalance ← 100Years ← 0WHILE Balance < 200 DO Balance ← Balance * 1.1 Years ← Years + 1ENDWHILEOUTPUT Years4.5
Input validation loop
Python's while loop becomes WHILE. Java's do … while becomes Cambridge's post-condition loop REPEAT … UNTIL, with the condition reversed by NOT.
mark = int(input("Mark (0-100): "))while mark < 0 or mark > 100: mark = int(input("Mark (0-100): "))print(mark)DECLARE Mark : INTEGEROUTPUT "Mark (0-100): "INPUT MarkWHILE Mark < 0 OR Mark > 100 DO OUTPUT "Mark (0-100): " INPUT MarkENDWHILEOUTPUT Mark4.6
Loop over every element of an array
Cambridge has no for-each loop, so the converter loops over the indexes of the array (its size is known from the declaration).
names = ["Ali", "Bea", "Cai"]for name in names: print(name)DECLARE Names : ARRAY[0:2] OF STRINGDECLARE I : INTEGERDECLARE Name : STRINGNames[0] ← "Ali"Names[1] ← "Bea"Names[2] ← "Cai"FOR I ← 0 TO 2 Name ← Names[I] OUTPUT NameNEXT I4.7
Nested loops
The inner loop runs completely for every pass of the outer loop (9 outputs here).
for row in range(1, 4): for col in range(1, 4): print(row * col)DECLARE Row : INTEGERDECLARE Col : INTEGERFOR Row ← 1 TO 3 FOR Col ← 1 TO 3 OUTPUT Row * Col NEXT ColNEXT Row4.8
Break / continue
Pseudocode standards have no break or continue, so they are copied and flagged. Rewrite the loop with a condition (see the linear search in Chapter 9).
nums = [4, -1, 7, 0, 3]for n in nums: if n < 0: continue if n == 0: break print(n)DECLARE Nums : ARRAY[0:4] OF INTEGERDECLARE I : INTEGERDECLARE N : INTEGERNums[0] ← 4Nums[1] ← -1Nums[2] ← 7Nums[3] ← 0Nums[4] ← 3FOR I ← 0 TO 4 N ← Nums[I] IF N < 0 THEN continue ENDIF IF N = 0 THEN break ENDIF OUTPUT NNEXT I- Not directly available in IGCSE: continue has no Cambridge pseudocode equivalent. It was copied unchanged.
- Not directly available in IGCSE: break has no Cambridge pseudocode equivalent. It was copied unchanged.
Exercises2
Q1.Add up the numbers from 1 to 10 and print the total.
total = 0for i in range(1, 11): total = total + iprint(total)Show answerHide answer
DECLARE Total : INTEGERDECLARE I : INTEGERTotal ← 0FOR I ← 1 TO 10 Total ← Total + INEXT IOUTPUT TotalQ2.Keep asking for a password until the user types "open".
word = input("Password: ")while word != "open": word = input("Password: ")print("Unlocked")Show answerHide answer
DECLARE Word : STRINGOUTPUT "Password: "INPUT WordWHILE Word <> "open" DO OUTPUT "Password: " INPUT WordENDWHILEOUTPUT "Unlocked"05Arrays & lists
Cambridge arrays have a fixed size and type, declared with DECLARE Name : ARRAY[0:n] OF TYPE. The converter uses a lower bound of 0 so your indexes stay the same, and fills the values one element at a time.
Examples7
5.1
Create with values
The array is declared with bounds [0:3] (four elements), then each element is assigned.
scores = [12, 7, 19, 5]print(scores[0])DECLARE Scores : ARRAY[0:3] OF INTEGERScores[0] ← 12Scores[1] ← 7Scores[2] ← 19Scores[3] ← 5OUTPUT Scores[0]5.2
Fixed-size array filled with 0
The array is declared with 5 elements and filled with 0 by a FOR loop.
counts = [0] * 5print(counts[2])DECLARE Counts : ARRAY[0:4] OF INTEGERDECLARE I : INTEGERFOR I ← 0 TO 4 Counts[I] ← 0NEXT IOUTPUT Counts[2]5.3
Read and update an element
Square brackets read and write one element; the index is unchanged.
stock = [3, 8, 2]stock[1] = stock[1] - 1print(stock[1])DECLARE Stock : ARRAY[0:2] OF INTEGERStock[0] ← 3Stock[1] ← 8Stock[2] ← 2Stock[1] ← Stock[1] - 1OUTPUT Stock[1]5.4
Length
A Cambridge array's size is fixed by its declaration, so the converter writes the number itself.
temps = [21, 25, 19, 23]print(len(temps))DECLARE Temps : ARRAY[0:3] OF INTEGERTemps[0] ← 21Temps[1] ← 25Temps[2] ← 19Temps[3] ← 23OUTPUT 4temps = [21, 25, 19, 23]last = temps[len(temps) - 1]print(last)DECLARE Temps : ARRAY[0:3] OF INTEGERDECLARE Last : INTEGERTemps[0] ← 21Temps[1] ← 25Temps[2] ← 19Temps[3] ← 23Last ← Temps[3]OUTPUT Last5.6
2-D array
A 2-D array is declared ARRAY[0:rows-1, 0:cols-1] and accessed with one pair of brackets: Grid[row, col].
grid = [[1, 2, 3], [4, 5, 6]]grid[1][2] = 0print(grid[0][1])DECLARE Grid : ARRAY[0:1, 0:2] OF INTEGERGrid[0, 0] ← 1Grid[0, 1] ← 2Grid[0, 2] ← 3Grid[1, 0] ← 4Grid[1, 1] ← 5Grid[1, 2] ← 6Grid[1, 2] ← 0OUTPUT Grid[0, 1]5.7
Add to a list
Cambridge arrays have a fixed size, so an empty list and append() cannot be converted. Declare an array big enough and keep a count of how many slots are used.
evens = []for i in range(1, 11): if i % 2 == 0: evens.append(i)print(evens)DECLARE Evens : <TYPE>DECLARE I : INTEGERevens = []FOR I ← 1 TO 10 IF MOD(I, 2) = 0 THEN evens.append(i) ENDIFNEXT IOUTPUT Evens- The type of evens could not be inferred.
- Not directly available in IGCSE: Cambridge arrays have a fixed size, so empty lists have no Cambridge pseudocode equivalent. It was copied unchanged.
- Not directly available in IGCSE: Cambridge arrays have a fixed size, so append() has no Cambridge pseudocode equivalent. It was copied unchanged.
Exercises1
Q1.Double every value in an array, then print the first one.
values = [3, 6, 9]for i in range(len(values)): values[i] = values[i] * 2print(values[0])Show answerHide answer
DECLARE Values : ARRAY[0:2] OF INTEGERDECLARE I : INTEGERValues[0] ← 3Values[1] ← 6Values[2] ← 9FOR I ← 0 TO 2 Values[I] ← Values[I] * 2NEXT IOUTPUT Values[0]06Strings
IGCSE has string functions: LENGTH(s), SUBSTRING(s, start, length), UCASE(s) and LCASE(s). SUBSTRING counts characters from 1.
Examples5
word = "algorithm"print(len(word))DECLARE Word : STRINGWord ← "algorithm"OUTPUT LENGTH(Word)6.2
One character
SUBSTRING(Word, 1, 1) takes 1 character from position 1. Positions start at 1, so index 0 becomes 1.
word = "algorithm"first = word[0]print(first)DECLARE Word : STRINGDECLARE First : STRINGWord ← "algorithm"First ← SUBSTRING(Word, 1, 1)OUTPUT Firstcity = "Paris"print(city.upper())print(city.lower())DECLARE City : STRINGCity ← "Paris"OUTPUT UCASE(City)OUTPUT LCASE(City)6.4
Compare two strings
Java must use .equals() to compare strings; in pseudocode it is an ordinary =.
password = input("Password: ")if password == "secret": print("Welcome")else: print("Wrong password")DECLARE Password : STRINGOUTPUT "Password: "INPUT PasswordIF Password = "secret" THEN OUTPUT "Welcome" ELSE OUTPUT "Wrong password"ENDIF6.5
Joining strings with numbers
IGCSE only joins values in OUTPUT (with commas), so this assignment is flagged. Output the parts with commas instead.
name = "Sam"score = 8message = name + " scored " + str(score)print(message)DECLARE Name : STRINGDECLARE Score : INTEGERDECLARE Message : STRINGName ← "Sam"Score ← 8Message ← name + " scored " + str(score)OUTPUT Message- Not directly available in IGCSE: String concatenation could not be converted to Cambridge pseudocode. It was copied unchanged.
Exercises1
Q1.Ask for a word and print how many characters it has.
word = input("Word: ")print(len(word))Show answerHide answer
DECLARE Word : STRINGOUTPUT "Word: "INPUT WordOUTPUT LENGTH(Word)07Subprograms
IGCSE separates PROCEDURE … ENDPROCEDURE (called with CALL) from FUNCTION … RETURNS TYPE … ENDFUNCTION. Every parameter has a type.
Examples5
7.1
Procedure with a parameter
A procedure is called with CALL Name(args). The parameter is given a type.
def greet(name): print("Hello " + name)greet("Kim")PROCEDURE Greet(Name : STRING) OUTPUT "Hello ", NameENDPROCEDURECALL Greet("Kim")7.2
Function returning a value
FUNCTION Name(params) RETURNS TYPE. The return type is required.
def area(width, height): return width * heightprint(area(4, 6))FUNCTION Area(Width : INTEGER, Height : INTEGER) RETURNS INTEGER RETURN Width * HeightENDFUNCTIONOUTPUT Area(4, 6)7.3
Function with no parameters
IGCSE writes a function with no parameters without brackets, in both the header and the call.
def getMark(): mark = int(input("Mark: ")) return markresult = getMark()print(result)DECLARE Result : INTEGERFUNCTION GetMark RETURNS INTEGER DECLARE Mark : INTEGER OUTPUT "Mark: " INPUT Mark RETURN MarkENDFUNCTIONResult ← GetMarkOUTPUT Result7.4
Procedure that changes an array
IGCSE does not say whether arrays are passed by reference, so the converter flags it: the caller's array may not change.
def reset(nums): for i in range(len(nums)): nums[i] = 0data = [4, 5, 6]reset(data)print(data[0])DECLARE Data : ARRAY[0:2] OF INTEGERPROCEDURE Reset(Nums : ARRAY[0:2] OF INTEGER) DECLARE I : INTEGER FOR I ← 0 TO 2 Nums[I] ← 0 NEXT IENDPROCEDUREData[0] ← 4Data[1] ← 5Data[2] ← 6CALL Reset(Data)OUTPUT Data[0]- Cambridge IGCSE pseudocode does not define whether arrays are passed by reference; the caller's array may not change.
7.5
Recursion (factorial)
A recursive function calls itself. It needs a base case (n <= 1) that stops the calls.
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1)print(factorial(5))FUNCTION Factorial(N : INTEGER) RETURNS INTEGER IF N <= 1 THEN RETURN 1 ENDIF RETURN N * Factorial(N - 1)ENDFUNCTIONOUTPUT Factorial(5)Exercises1
Q1.Write a function that returns the larger of two numbers.
def larger(a, b): if a > b: return a return bprint(larger(3, 8))Show answerHide answer
FUNCTION Larger(A : INTEGER, B : INTEGER) RETURNS INTEGER IF A > B THEN RETURN A ENDIF RETURN BENDFUNCTIONOUTPUT Larger(3, 8)08Random numbers
IGCSE has RANDOM(), which gives a real number from 0 to 1. A whole number range is built with ROUND and arithmetic.
Examples1
8.1
Dice roll (1–6)
RANDOM() * 5 gives 0–5; rounding and adding 1 gives a whole number from 1 to 6.
import randomroll = random.randint(1, 6)print(roll)DECLARE Roll : INTEGERRoll ← ROUND(RANDOM() * 5, 0) + 1OUTPUT RollExercises1
Q1.Pick a random number from 1 to 100 and print whether it is above 50.
import randomn = random.randint(1, 100)if n > 50: print("high")else: print("low")Show answerHide answer
DECLARE N : INTEGERN ← ROUND(RANDOM() * 99, 0) + 1IF N > 50 THEN OUTPUT "high" ELSE OUTPUT "low"ENDIF09Complete programs
These are the standard algorithms examiners ask for. Each one combines variables, loops, selection and arrays from the earlier chapters. Read the pseudocode line by line and match it to the source.
Examples5
9.1
Linear search
Checks each element in turn and stops when the target is found. A found flag in the loop condition is used instead of break.
names = ["Ali", "Bea", "Cai", "Dev"]target = input("Name: ")found = Falsei = 0while i < len(names) and not found: if names[i] == target: found = True else: i = i + 1if found: print("Found at", i)else: print("Not found")DECLARE Names : ARRAY[0:3] OF STRINGDECLARE Target : STRINGDECLARE Found : BOOLEANDECLARE I : INTEGERNames[0] ← "Ali"Names[1] ← "Bea"Names[2] ← "Cai"Names[3] ← "Dev"OUTPUT "Name: "INPUT TargetFound ← FALSEI ← 0WHILE I < 4 AND NOT Found DO IF Names[I] = Target THEN Found ← TRUE ELSE I ← I + 1 ENDIFENDWHILEIF Found THEN OUTPUT "Found at", I ELSE OUTPUT "Not found"ENDIF9.2
Total and average
Start the total at 0, add each element, then divide by the number of elements. The average is a real number.
marks = [56, 78, 91, 64, 70]total = 0for m in marks: total = total + maverage = total / len(marks)print(total)print(average)DECLARE Marks : ARRAY[0:4] OF INTEGERDECLARE Total : INTEGERDECLARE I : INTEGERDECLARE M : INTEGERDECLARE Average : REALMarks[0] ← 56Marks[1] ← 78Marks[2] ← 91Marks[3] ← 64Marks[4] ← 70Total ← 0FOR I ← 0 TO 4 M ← Marks[I] Total ← Total + MNEXT IAverage ← Total / 5OUTPUT TotalOUTPUT Average9.3
Maximum value
Assume the first element is the largest, then compare it with every other element.
temps = [18, 24, 21, 27, 19]highest = temps[0]for i in range(1, len(temps)): if temps[i] > highest: highest = temps[i]print(highest)DECLARE Temps : ARRAY[0:4] OF INTEGERDECLARE Highest : INTEGERDECLARE I : INTEGERTemps[0] ← 18Temps[1] ← 24Temps[2] ← 21Temps[3] ← 27Temps[4] ← 19Highest ← Temps[0]FOR I ← 1 TO 4 IF Temps[I] > Highest THEN Highest ← Temps[I] ENDIFNEXT IOUTPUT Highest9.4
Counting matches
A counter starts at 0 and goes up by 1 each time an element meets the condition.
marks = [45, 82, 67, 39, 90]passes = 0for m in marks: if m >= 50: passes = passes + 1print(passes)DECLARE Marks : ARRAY[0:4] OF INTEGERDECLARE Passes : INTEGERDECLARE I : INTEGERDECLARE M : INTEGERMarks[0] ← 45Marks[1] ← 82Marks[2] ← 67Marks[3] ← 39Marks[4] ← 90Passes ← 0FOR I ← 0 TO 4 M ← Marks[I] IF M >= 50 THEN Passes ← Passes + 1 ENDIFNEXT IOUTPUT Passes9.5
Bubble sort
Compare neighbours and swap them if they are in the wrong order. After each pass the largest remaining value is at the end, so the inner loop gets shorter.
data = [5, 2, 9, 1, 7]n = len(data)for i in range(n - 1): for j in range(n - 1 - i): if data[j] > data[j + 1]: temp = data[j] data[j] = data[j + 1] data[j + 1] = tempfor x in data: print(x)DECLARE Data : ARRAY[0:4] OF INTEGERDECLARE N : INTEGERDECLARE I : INTEGERDECLARE J : INTEGERDECLARE Temp : INTEGERDECLARE K : INTEGERDECLARE X : INTEGERData[0] ← 5Data[1] ← 2Data[2] ← 9Data[3] ← 1Data[4] ← 7N ← 5FOR I ← 0 TO N - 2 FOR J ← 0 TO N - 1 - I - 1 IF Data[J] > Data[J + 1] THEN Temp ← Data[J] Data[J] ← Data[J + 1] Data[J + 1] ← Temp ENDIF NEXT JNEXT IFOR K ← 0 TO 4 X ← Data[K] OUTPUT XNEXT KExercises2
Q1.Find the smallest value in an array.
nums = [8, 3, 11, 5]lowest = nums[0]for i in range(1, len(nums)): if nums[i] < lowest: lowest = nums[i]print(lowest)Show answerHide answer
DECLARE Nums : ARRAY[0:3] OF INTEGERDECLARE Lowest : INTEGERDECLARE I : INTEGERNums[0] ← 8Nums[1] ← 3Nums[2] ← 11Nums[3] ← 5Lowest ← Nums[0]FOR I ← 1 TO 3 IF Nums[I] < Lowest THEN Lowest ← Nums[I] ENDIFNEXT IOUTPUT LowestQ2.Count how many times the letter "a" appears in a word.
word = "banana"count = 0for i in range(len(word)): if word[i] == "a": count = count + 1print(count)Show answerHide answer
DECLARE Word : STRINGDECLARE Count : INTEGERDECLARE I : INTEGERWord ← "banana"Count ← 0FOR I ← 0 TO LENGTH(Word) - 1 IF SUBSTRING(Word, I + 1, 1) = "a" THEN Count ← Count + 1 ENDIFNEXT IOUTPUT Count