0% found this document useful (0 votes)
9 views47 pages

2D Arrays Problems and Solutions

The document provides detailed pseudocode and Python code examples for working with 2D arrays, including initialization, user input, and various operations such as displaying contents, updating values, and calculating sums. It covers multiple problems that demonstrate how to manipulate 2D arrays, including displaying original and final arrays, counting elements based on conditions, and resetting arrays. Each section includes both pseudocode and Python implementations for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views47 pages

2D Arrays Problems and Solutions

The document provides detailed pseudocode and Python code examples for working with 2D arrays, including initialization, user input, and various operations such as displaying contents, updating values, and calculating sums. It covers multiple problems that demonstrate how to manipulate 2D arrays, including displaying original and final arrays, counting elements based on conditions, and resetting arrays. Each section includes both pseudocode and Python implementations for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

2D Arrays

1
Pseudocode for known set of data

DECLARE twoDarray : ARRAY [1:3, 1:3] OF INTEGER

twoDarray ← [[1,2,3]
[4,5,6]
[7,8,9]]

OUTPUT twoDarray[3,3] // Outputs 9


OUTPUT twoDarray[2,2] // Outputs 8

FOR i ← 1 to 3 // iterate through the rows


​ FOR j ← 1 to 3 // iterate through the columns
​ ​ OUTPUT twoDarray[i][j], “ “
​ NEXT j
NEXT i

Python for known set of data

twoDarray = [[1,2,3],
[4,5,6],
[7,8,9]]

for i in range(3):
​ for i in range(3):
​ ​ print(twoDarray[i][j],end= “ “) # adds a space between each value
​ print()

2
Pseudocode for unknown set of data and 2D array setup

DECLARE rows, columns : INTEGER

OUTPUT “Number of rows: “


INPUT rows
OUTPUT “Number of columns: “
INPUT columns

DECLARE grid : ARRAY [1:rows, 1: columns] OF INTEGER

FOR i ← 1 TO rows
​ FOR j ← 1 TO columns
​ ​ OUTPUT “Enter a value: “
​ ​ INPUT grid[i][j]
​ NEXT j
NEXT i

FOR x ← 1 TO row
​ FOR y ← 1 TO columns
​ ​ OUTPUT grid[x][y]
​ NEXT y
NEXT x

Python for unknown set of data and 2D array setup

grid = [ ]

rows = int(input(”Enter number of rows: “))


columns = int(input(”Enter number of columns: “))

for i in range(rows):
​ rowList=[ ] # stores the values of the row
​ for j in range(columns):
​ ​ value=int(input(“Enter a number: “)) #holds the value the user has entered
​ ​ rowList.append(value)
​ grid.append(rowList)
print(grid) # Not an effective method of displaying contents of an array

3
Problem 1

Write the pseudocode and Python program to display a 2D array with the following
contents. Initialize the 2D array with 0 to start with.

Original array
​ 0 ​ 0 ​ 0
​ 0 ​ 0 ​ 0
​ 0 ​ 0 ​ 0

Final array
​ X ​ 0 ​ 0
​ 0 ​ X ​ 0
​ 0 ​ 0 ​ X

pseudocode:

DECLARE grid : ARRAY [1:3, 1:3] of STRING

grid ← [[O,O,O] // Letter O not number zero


[O,O,O]
[O,O,O]]

for i ← 1 TO 3
for j ← 1 TO 3
OUTPUT grid[i][j]
NEXT j
NEXT i

// method 1
INPUT grid[1][1] ← “X”
INPUT grid[2][2] ← “X”
INPUT grid[3][3] ← “X”

// method 2
for x ← 1 TO 3
for y ← 1 TO 3
IF y = x // If both y and x are equal, it will update the value to x
grid[i][j] ← “X”

4
NEXT y
NEXT x

for a ← 1 TO 3
for b ← 1 TO 3
OUTPUT grid[a][b], “ “
NEXT b
NEXT a

python:

#initialise
array = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
#display original array
print("Original array:")
for i in range (3):
for j in range (3):
print(array[i][j], end=" ")
print() #creates a new line
array[0][0] = 'X'
array[1][1] = 'X'
array[2][2] = 'X'
#display final array
print("Final array:")
for x in range (3):
for y in range (3):
print(array[x][y], end=" ")
print() #creates a new line

5
Problem 2

Write the pseudocode and Python program to initialize a 2D array with the following
contents:
[[2,3,4],
[5,6,7],
[8,9,10]]

Display back the contents in a 2D grid / matrix format then update every element on the
second column to 1.
Display back the updated 2D array in grid / matrix format

Original array :
​ 2 ​ 3 ​ 4
​ 5 ​ 6 ​ 7
​ 8 ​ 9 ​ 10

Final array
​ 2 ​ 1 ​ 4
​ 5 ​ 1 ​ 7
​ 8 ​ 1 ​ 10

Python

Python
array = [[2,3,4],
[5,6,7],
[8,9,10]]
print (“original array: ”)

for i in range(3):
for j in range(3):
print(array[i][j], end=" ")
print()
for i in range(3):
array[i][1] = 1

print ("final array is: ")


for i in range(3):
for j in range(3):
print(array[i][j], end=" ")
print()

6
Pseudocode

DECLARE twoDarray : ARRAY [1:3 , 1:3] OF INTEGER


twoDarray ← [[2,3,4],
[5,6,7],
[8,9,10]]
OUTPUT “original array:”
FOR row ← 1 TO 3
FOR col ← 1 TO 3
OUTPUT twoDarray[row, col], “ “
NEXT col
NEXT row
FOR row ← 1 TO 3
twoDarray[row][2] ← 1
NEXT row
OUTPUT”final array is:”
FOR row ← 1 TO 3
FOR col ← 1 TO 3
OUTPUT twoDarray[row, col],” “,
NEXT col
NEXT row

7
Problem 3

Write the pseudocode and Python program to initialize a 2D array with the following
contents:
[[12, 13, 44],
[15, 16, 17],
[88, 91, 100]]

Display back the contents in a 2D grid / matrix format.


Use a procedure to calculate division 4
Finally, display those numbers which are divisible by 4

Original array :
​ 12 ​ 13 ​ 44
​ 15 ​ 16 ​ 17
​ 88 ​ 91 ​ 100

Divisible by 4:
12​ 44​ 16​ 88​ 100

//procedure definition
PROCEDURE divisible_by4()
​ FOR i ← 1 TO 3
​ ​ FOR j ← 1 TO 3
​ ​ ​ IF twoDarry[i][j] MOD 4 = 0 THEN
​ ​ ​ ​ OUTPUT(twoDarry[i][j])
​ ​ ​ ENDIF
​ ​ NEXT j
​ NEXT i
END PROCEDURE

//main program
DECLARE twoDarray: ARRAY [1:3,1:3] OF INTEGER
twoDarray ← [[12, 13, 44], [15, 16, 17], [88, 91, 100]]
DECLARE rows, cols, divby4 : INTEGER

FOR i ← 1 TO 3
FOR j ← 1 TO 3
OUTPUT twoDarray[i,j] , " "
NEXT j
NEXT i

8
OUTPUT "Numbers divisible by 4:"
CALL divisible_by4()

Python:

Python

#function defintion
def divisble_by4():
for i in range(3):
for j in range(3):
if twoDarray[i][j] % 4 == 0:
print(twoDarray[i][j], end = " ")
#main program
twoDarray = [[12,13,44],
​ ​ [15,16,17],
[88,91,100]]

for i in range(rows):
for j in range(cols):
print(twoDarray[i][j],end=" ")
print()
divisble_by4() #function call

9
Problem 4

Write the pseudocode and python program to store numbers in a NXN 2D array. Display the
sum of numbers on antidiagonal (green highlighted). Below is a sample run of the program:

Sum of antidiagonal elements is calculated as 4+7+10+13

DECLARE array : ARRAY[1:4,1:4] OF INTEGER


DECLARE row, column, total : INTEGER

array ← [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
total ← 0

FOR i ← 1 TO 4
FOR j ← 1 TO 4
OUTPUT array[i][j], " "

column ← 4
FOR i ← 1 TO 4
total ← total + array[i][column]
column ← column - 1

OUTPUT total

10
Python

# Declare and initialize the 2D array

array = [

[1, 2, 3, 4],

[5, 6, 7, 8],

[9, 10, 11, 12],

[13, 14, 15, 16]

# Initialize total

total = 0

# Print the 2D array (similar to nested loop in pseudocode)

for i in range(4):

for j in range(4):

print(array[i][j], end=" ")

print() # Move to the next line after each row

# Sum the secondary diagonal

column = 3 # In Python, indexing starts from 0, so column 4 is index 3

for i in range(4):

total = total + array[i][column]

column = column - 1 # Move left in the column

# Output the total

print("Total:", total)

11
Problem 5
Write the pseudocode and python program to input the number of rows and the number of
columns. User then populates the 2D array with numbers. Display the sum of numbers in
each row and each column. Below is a sample run of the program:

Number of rows:3
Number of columns:2
Enter the entries row-wise:
12
34
56

Sum of row: 1 is: 3


Sum of row: 2 is: 7
Sum of row: 3 is: 11
Sum of column: 1 is: 9
Sum of column: 2 is: 12

DECLARE row, column, totalrow, totalcolumn : INTEGER

OUTPUT “Enter number of rows”


INPUT row
OUTPUT “Enter number of columns”
INPUT column

DECLARE numarray : ARRAY[1:row, 1:column] OF INTEGER

FOR i ← 1 TO row
FOR j ← 1 TO column
OUTPUT “Enter value”
INPUT numarray[i,j]
NEXT j
NEXT i

FOR i ← 1 TO row
​ totalrow ← 0
​ FOR j ← 1 TO column
​ ​ totalrow ← totalrow + numarray[i,j]
​ NEXT j
​ OUTPUT “Sum of row:”,i,”is:”,totalrow
NEXT i

FOR i ← 1 TO column
​ totalcolumn ← 0
​ FOR j ← 1 TO row
​ ​ totalcolumn ← totalcolumn + numarray[j,i]

12
​ NEXT j
​ OUTPUT “Sum of column:”,j,”is:”,totalcolumn
NEXT i

Python

row = int(input("Number of rows: "))

column = int(input("Number of columns: "))

array = []

print("Enter the entries row-wise: ")

for i in range(row):

temp = []

for j in range(column):

num=int(input())

temp.append(num)

array.append(temp)

print("\n")

for i in range(row):

for j in range(column):

print(array[i][j], end= " ")

print()

print("\n")

13
for i in range(row):

row_sum = 0

for j in range(column):

row_sum = row_sum + array[i][j]

print("Sum of row", i + 1, "is:", row_sum)

print("\n")

for j in range(column):

col_sum = 0

for i in range(row):

col_sum = col_sum + array[j][i]

print("Sum of column", j + 1, "is:", col_sum)

14
Problem 6

Write the pseudocode and Python program to input numbers (take user input) into a 2D
array (size determined by the user), display back the contents in a grid format. After this,
reset the array so that all the numbers are updated to 0.

Sample input array:

10 4 9
7 2 5
1 8 3

Output array:

0 0 0
0 0 0
0 0 0

DECLARE row, column : INTEGER

OUTPUT “Enter number of rows”


INPUT row
OUTPUT “Enter number of columns”
INPUT column

DECLARE numarray : ARRAY[1:row, 1:column] OF INTEGER

FOR i ← 1 TO row
FOR j ← 1 TO column
OUTPUT “Enter value”
INPUT numarray[i,j]
NEXT j
NEXT i

FOR i ← 1 TO row
FOR j ← 1 TO column
OUTPUT numarray[i,j], “ “
NEXT j
NEXT i

FOR i ← 1 TO row
FOR j ← 1 TO column

15
numarray[i,j] ← 0
NEXT j
NEXT i

FOR i ← 1 TO row
FOR j ← 1 TO column
OUTPUT numarray[i,j], “ ”
NEXT j
OUTPUT newline
NEXT i

Python

rows = int(input("Enter the number of rows: "))

columns = int(input("Enter the number of columns: "))

array = []

for i in range(rows):

temp = []

for j in range(columns):

num = int(input("Enter element: "))

temp.append(num)

array.append(temp)

print("\n")

for i in range(rows):

for j in range(columns):

print(array[i][j], end= " ")

print()

for i in range(rows):

16
for j in range(columns):

array[i][j] = 0


print("\n")

for i in range(rows):

for j in range(columns):

print(array[i][j], end= " ")

print()

17
Problem 7

Write the pseudocode and Python program to input numbers (take user input) into a 2D
array (size determined by the user), display back the contents in a grid format. Display the
count of numbers smaller than 5 and count of numbers equal to or bigger than 5.

Sample input array:

10 14 19
7 21 5
1 8 3

Output:
Count of numbers bigger than 5 is : 6
Count of numbers smaller than 5 is : 3

18
Pseudocode:
DECLARE countover5, countunder5 : INTEGER
countover5←0
countunder5← 0

OUTPUT “ Please enter the number of rows in the array”


INPUT user_input_rows
OUTPUT “Please enter the number of columns in the array”
INPUT user_input_columns

DECLARE gridlist : ARRAY[1:user_input_rows, 1:user_input_columns] OF INTEGER


FOR i ←1 to user_input_rows
FOR k ←1 to user_input_columns
INPUT gridlist[i,k]
NEXT k
​ NEXT i

FOR i ←1 to user_input_rows
FOR k ←1 to user_input_columns
OUTPUT gridlist[i,k], “ “
IF gridlist[i,k] >= 5 THEN
​ ​ countover5← countover5 + 1
​ ELSE
countunder5← countunder5+1
​ ENDIF
​ ​ NEXT k
​ ​ ​ OUTPUT newline
​ NEXT i

​ OUTPUT “ Count number greater than 5 is: ”, countover5


​ OUTPUT “ Count number less than 5 is: ,” countunder5

19
Python:

Python

# Initialize counters

count_over_five = 0

count_under_five = 0

# Get grid dimensions

rows = int(input("Please enter the number of rows in the array: "))

columns = int(input("Please enter the number of columns in the array: "))

# Initialize the grid (empty list)

grid = []

# Populate the grid with user input

for i in range(rows):

rowList = [] # Create a new row

for k in range(columns):

value = int(input("Enter value: ")) # Show row & column position

rowList.append(value) # Append value to the row

grid.append(rowList) # Add the row to the grid (correct way)

# Display the grid

print("\nGrid:")

for i in range(rows):

for k in range(columns):

print(grid[i][k], end=" ") # Print each element with space

20
print() # Move to the next line after each row

# Count numbers based on the condition

for i in range(rows):

for k in range(columns):

if grid[i][k] >= 5:

count_over_five += 1

else:

count_under_five += 1

# Display the results

print("\nCount of numbers greater than or equal to 5:", count_over_five)

print("Count of numbers less than 5:", count_under_five)

21
Problem 8

Write the pseudocode and Python program to input numbers into a 2D array (size
determined by the user), display back the contents in a grid format. Copy every alternate
element into a separate 1D array. Display back this array.

Sample input array:

10 14 19
7 21 5
1 8 3

Output:
10 19 21 1 3

Pseudocode

DECLARE row, column : INTEGER

OUTPUT “Enter number of rows”


INPUT row

OUTPUT “Enter number of columns”


INPUT column

DECLARE twoDarray : ARRAY[1:row, 1:column] OF INTEGER


DECLARE oneDarray : ARRAY [1:5] OF INTEGER

FOR i← 1 TO row
FOR j← 1 TO column
OUTPUT(“Enter a value: ”)
INPUT twoDarray[i, j]
NEXT j
NEXT i

counter←0
FOR i← 1 TO row
FOR j← 1 TO column
IF counter MOD 2 = 0 THEN
oneDarray[counter] ← twoDarray[i, j]
ENDIF
counter←counter+1
NEXT j
NEXT i

FOR i ← 1 TO counter
OUTPUT oneDarray[i]
NEXT i

22
Python
# Get grid size from the user
rows = int(input("Enter number of rows: "))
columns = int(input("Enter number of columns: "))

# Initialize 2D list
twoDarray = []

# Fill the 2D array with user input


print("Enter the numbers row by row:")
for i in range(rows):
row = [] # Create a new row
for j in range(columns):
value = int(input(f"Enter value: ")) # Use (i+1, j+1) for better
understanding
row.append(value) # Add value to the row
twoDarray.append(row) # Add row to the 2D array

# Initialize 1D list for even-indexed values


oneDarray = []
counter = 0 # This will track the position of the 2D array which is an odd
number

# Flatten the 2D list and pick even index positions


for i in range(rows):
for j in range(columns):
if counter % 2 == 0: # Only pick values at even positions
oneDarray.append(twoDarray[i][j])
counter = counter + 1 # Move to the next index

# Display the result


print("\n2D Array (Grid):")
for row in twoDarray:
print(row) # Print each row nicely

print("\n1D Array (Even-indexed values):", oneDarray)

23
Problem 9 - Challenge

Write the pseudocode and Python program to store three assessments’ marks (on 100) of 4
students into a 2D array. The names of the students are stored in a 1D array such that the
first name corresponds to the first row of marks (for the three assessments).
-​ Display back all the marks in a 2D grid format
-​ Display the name of the student with the highest average marks (across the
three assessments).

Sample input arrays:

Names
Alan Kacie Jake Ivy

Marks
90 89 78
85 83 82
65 67 68
87 79 80

24
Pseudocode

DECLARE names : ARRAY [1:4] OF STRING


DECLARE marks : ARRAY[1:4,1:3] OF REAL

// Initialise the arrays


names ← [“alan”, “kacie”,”jake”,”ivy”]
marks ← [
[90, 89, 78],
[85, 83, 82],
[65, 67, 68],
[87, 79, 80]]

// Display
OUTPUT ("Marks of students: ")
OUTPUT ("Name Assessment 1 Assessment 2 Assessment 3")

FOR i ← 1 TO 4 // The length of names array


OUTPUT names[i], " ", // Print the student name
FOR j ← 1 TO 3 // The columns of the marks array
OUTPUT marks[i,j], “ “
NEXT j
NEXT i

// Calculate average
Highest_average ← -1
Top_student ← “ “

FOR i ← 1 TO 4 // The length of names array


student_total ← 0
FOR j ← 1 TO 3 // The columns of the marks array
student_total ← student_total + marks[i,j]
NEXT j
student_average ← student_total / 3 //
IF student_average > highest_average THEN
highest_average ← student_average
top_student ← names[i]
ENDIF
NEXT i

OUTPUT ("Student with the highest average marks: ", top_student, " with an average of ",
highest_average)

25
Python

# Initialise the arrays


names = ["Alan", "Kacie", "Jake", "Ivy"]
marks = [
[90, 89, 78],
[85, 83, 82],
[65, 67, 68],
[87, 79, 80]]

# Display student marks


print("Marks of students:")
print("Name Assessment 1 Assessment 2 Assessment 3")

for i in range(4):
print(names[i])
for j in range(3):
print(marks[i][j], end=" ") # Print each element with space
print() # Move to the next line after each row

# Calculate the highest average


highest_average = -1
top_student = ""
average = 0

for i in range(len(names)):
average = sum(marks[i]) / len(marks[i]) # Calculate the average score
if average > highest_average:
highest_average = average
top_student = names[i]

# Display the top student


print("Student with the highest average marks: ",top_student," with an average of
",average)

26
Problem 10
Write the pseudocode and Python program that finds and returns the largest element in a given 2D array. Let
the user decide the dimensions of the array and the numbers within the array.

Sample array:

5 12 8

15 3 10

2 18 7

Sample output:

The largest element in the 2D array is: 18

DECLARE row, column, maxvalue : INTEGER

OUTPUT “Enter number of rows: ”


INPUT row
OUTPUT “Enter number of columns: ”
INPUT column

DECLARE numbers : ARRAY[1:row, 1:column] OF INTEGER

FOR i ← 1 TO row
​ FOR j ← 1 TO column
​ ​ OUTPUT “Enter Value: ”
​ ​ INPUT numbers[i,j]
​ NEXT j
NEXT i

maxvalue ← numbers[0,0]

FOR i ← 1 TO row
​ FOR j ← 1 TO column
​ ​ IF numbers[i,j] > maxvalue THEN
​ ​ ​ maxvalue ← numbers[i,j]
​ ​ ENDIF
​ NEXT j
NEXT i

OUTPUT “The largest element in the 2D array is: ”,maxvalue

27
Python

rows = int(input("Enter the number of rows: "))

columns = int(input("Enter the number of columns: "))

array = []

for i in range(rows):

temp = []

for j in range(columns):

num = int(input("Enter element at position: "))

temp.append(num)

array.append(temp)

for i in range(rows):

for j in range(columns):

print(array[i][j], end= " ")

print()

max_num = array[0][0]

for i in range(rows):

for j in range(columns):

if array[i][j] > max_num:

max_num = array[i][j]

print("The largest element in the array is: ", max_num)

28
Problem 11

Given the following parallel arrays:

employees = ["John", "Sarah", "Alex"]

salaries = [50000, 60000, 55000]

Write the pseudocode and Python program that finds the salary of the given employee’s name.

Pseudocode:

DECLARE employees : ARRAY [1:3] OF STRING ← ["John", "Sarah", "Alex"]


DECLARE salaries : ARRAY [1:3] OF INTEGER ← [50000, 60000, 55000]
DECLARE searchName : STRING
DECLARE found : BOOLEAN
DECLARE index : INTEGER

OUTPUT "Enter the employee's name: "


INPUT searchName

found ← FALSE // Default value indicating employee not found

// Linear search for the employee's salary


FOR index ← 1 TO 3 DO
​ IF employees[index] = searchName THEN
​ OUTPUT "Salary of ", searchName, " is $", salaries[index]
​ found ← TRUE
​ ENDIF
NEXT index

// Output message if employee not found


IF found = FALSE THEN
​ OUTPUT "Employee not found."
ENDIF

29
Python

employees = ["John", "Sarah", "Alex"]

salaries = [50000, 60000, 55000]

employee = input("Which employee do you want to know the salary of:


")

found = False # Flag to check if employee exists

for x in range(3):

if employee == employees[x]:

print(salaries[x])

found = True # Mark as found

break # Exit loop once found

if not found:

print("Employee doesn't exist")

30
Problem 12
Given:

cities = ["New York", "London", "Tokyo"]

temperatures = [30, 22, 35] # in Celsius

Write the pseudocode and Python to find the city with the highest temperature.

Pseudocode

DECLARE cities : ARRAY [1:3] OF STRING


DECLARE temperatures : ARRAY [1:3] OF INTEGER
DECLARE maxTemp : INTEGER
DECLARE maxCity : STRING
DECLARE index : INTEGER

cities ← ["New York", "London", "Tokyo"]


temperatures ← [30, 22, 35]

// Initialize maxTemp with the first temperature and maxCity with the first city
maxTemp ← temperatures[1]
maxCity ← cities[1]

// Loop through the array to find the highest temperature


FOR index ← 2 TO 3 // Starting at 2 as first element is used to store in maxTemp
​ IF temperatures[index] > maxTemp THEN
​ maxTemp ← temperatures[index]
​ maxCity ← cities[index]
​ ENDIF
NEXT index

OUTPUT "The city with the highest temperature is ", maxCity, " with ", maxTemp, "°C"

31
Python
# Data initialization
cities = ["New York", "London", "Tokyo"]
temperatures = [30, 22, 35]

# Initialize maxTemp and maxCity


maxTemp = temperatures[0]
maxCity = cities[0]

# Loop to find the city with the highest temperature


for index in range(1, len(temperatures)):
if temperatures[index] > maxTemp:
maxTemp = temperatures[index]
maxCity = cities[index]

# Output the result


print("The city with the highest temperature
is",maxCity,"with",maxTemp,"°C")

32
Problem 13
Write the pseudocode and Python program that returns the row and column index of an element (input by the
user) in the matrix. Display an appropriate message if the element is not found.

Sample array:

5 12 8

15 3 10

2 18 7

Enter the element to search: 10

Sample output:

Element 10 found at row index 1 and column index 2

PYTHON

#define the matrix


matrix = [
[5, 12, 8],
[15, 3, 10],
[2, 18, 7]
]
#find the element
target = int(input("Enter the element to search: "))
#indicator
found = False
#find the element
for i in range(3):
for j in range(3):
if matrix[i][j] == target:
print("The element",target,"is present in the matrix at row",i+1,"and column",j+1)
found = True
break
if found:
break
#if element is not found
if not found:
print(f"The element",target,"is not present in the matrix.")

33
PSEUDOCODE - FOR Loop

DECLARE matrix : ARRAY[1:3,1:3] OF INTEGER


DECLARE searchElement : INTEGER
DECLARE rowIndex, colIndex : INTEGER
DECLARE found : BOOLEAN

// Define the matrix


matrix ← [
[5, 12, 8],
[15, 3, 10],
[2, 18, 7]
]

OUTPUT "Enter the element to search: "


INPUT searchElement

found ← FALSE

// Search for the element in the matrix


FOR rowIndex ← 1 TO 3
FOR colIndex ← 1 TO 3
IF matrix[rowIndex, colIndex] = searchElement THEN
OUTPUT "The element ", searchElement, " is present in the matrix at row ", rowIndex, " and column ",
colIndex
found ← TRUE
EXIT // Exit inner loop
ENDIF
NEXT colIndex
IF found = TRUE THEN
EXIT // Exit outer loop if element is found
ENDIF
NEXT rowIndex

// If element is not found


IF found = FALSE THEN
OUTPUT "The element ", searchElement, " is not present in the matrix."
ENDIF

34
PSEUDOCODE - While Loop

DECLARE matrix : ARRAY [1:3, 1:3] OF INTEGER


DECLARE searchElement : INTEGER
DECLARE rowIndex : INTEGER
DECLARE colIndex : INTEGER
DECLARE found : BOOLEAN

matrix ← [
[5, 12, 8],
[15, 3, 10],
[2, 18, 7]
]

OUTPUT "Enter the element to search: "


INPUT searchElement

found ← FALSE
rowIndex ← 1

// Search for the element using WHILE loop with flag


WHILE rowIndex <= 3 AND found = FALSE
​ colIndex ← 1 // Reset column index for each row

​ WHILE colIndex <= 3 AND found = FALSE


​ IF matrix[rowIndex, colIndex] = searchElement THEN
​ OUTPUT "Element ", searchElement, " found at row index ", rowIndex - 1, " and column
index ", colIndex - 1
​ found ← TRUE
​ ENDIF
​ colIndex ← colIndex + 1
​ ENDWHILE

​ rowIndex ← rowIndex + 1
ENDWHILE

// If element is not found, display message


IF found = FALSE THEN
​ OUTPUT "Element not found in the matrix."
ENDIF

35
Problem 14

Write the pseudocode and Python program that uses a bubble sort to reorder the set of names in ascending
order that appears in the 1D array. The 1D array should be initialised with the following data:

Original array :
David, John, Danielle, Tim, Jan, Sean, Scott, Josh, Amy

Updated array
Amy, Danielle, David, Jan, John, Josh, Scott, Sean, Tim

PYTHON

# Step 1: Initialize the 1D array


Name = ["David", "John", "Danielle", "Tim", "Jan", "Sean", "Scott", "Josh", "Amy"]

# Step 2: Bubble Sort


NumItems = len(Name) - 1

while NumItems > 1:


for Item in range(NumItems):
if Name[Item] > Name[Item + 1]: # Swap if out of order
Name[Item], Name[Item + 1] = Name[Item + 1], Name[Item]
NumItems -= 1 # Reduce sorting range

# Step 3: Output the sorted names


for name in Name:
print(name)

36
PSEUDOCODE

DECLARE Name : ARRAY[1:9] OF STRING

// Step 1: Initialize the 1D array


Name ← ["David","John", "Danielle", "Tim", "Jan", "Sean", "Scott", "Josh", "Amy"]

// Step 2: Bubble Sort (Ascending Order)


// Makes sure the last item doesn’t exceed beyond the list
NumItems ← LENGTH(Name) - 1

WHILE NumItems > 1 DO


FOR Item ← 1 TO NumItems DO
IF Name[Item] > Name[Item + 1] THEN // Swap if out of order
DECLARE Temp ← Name[Item]
Name[Item] ← Name[Item + 1]
Name[Item + 1] ← Temp
ENDIF
NEXT Item
NumItems ← NumItems - 1
ENDWHILE

// Step 3: Output the sorted names


FOR i ← 1 TO 9 DO
OUTPUT Name[i]
NEXT i

37
Problem 15

Write the pseudocode and Python program that uses a bubble sort to reorder the set of numbers in
descending order that appears in the 1D array. Ask the user for a set of 10 integer numbers:

PYTHON

# Step 1: Get user input


Numbers = [0] * 10 # Create a list of size 10 with placeholder values

for i in range(10): # Using range(10) (0-based indexing)


Numbers[i] = int(input("Enter number: ")) # Adjust for display

# Step 2: Bubble Sort (Descending Order)


NumItems = len(Numbers) - 1

while NumItems > 1:


for Item in range(NumItems): # Using range(10) directly
if Numbers[Item] < Numbers[Item + 1]: # Swap for descending order
Numbers[Item], Numbers[Item + 1] = Numbers[Item + 1], Numbers[Item]
NumItems -= 1 # Reduce sorting range

# Step 3: Output the sorted numbers


print("\nSorted numbers in descending order:")
for num in Numbers:
print(num)

38
PSEUDOCODE

DECLARE Numbers : ARRAY[1:10] OF INTEGER

// Step 1: Get user input


FOR i ← 1 TO 10 DO
OUTPUT "Enter a number: "
INPUT Numbers[i]
NEXT i

// Step 2: Bubble Sort (Descending Order)


NumItems ← LENGTH(Numbers) - 1

WHILE NumItems > 1 DO


FOR Item ← 1 TO NumItems DO
IF Numbers[Item] < Numbers[Item + 1] THEN // Swap for descending order
DECLARE Temp ← Numbers[Item]
Numbers[Item] ← Numbers[Item + 1]
Numbers[Item + 1] ← Temp
ENDIF
NEXT Item
NumItems ← NumItems - 1
ENDWHILE

// Step 3: Output the sorted numbers


FOR i ← 1 TO 10 DO
OUTPUT Numbers[i]
NEXT i

39
Problem 16
Write the pseudocode and Python program that counts the number of times an element (input by the user)
appears in the matrix.

Sample array:

5 12 8

15 3 10

2 12 7

Enter the element to count: 12

Sample output:

Element 12 appears 2 times in the matrix.

DECLARE matrix : ARRAY [1:3, 1:3] OF INTEGER


DECLARE searchElement : INTEGER
DECLARE rowIndex : INTEGER
DECLARE colIndex : INTEGER
DECLARE count : INTEGER
matrix ← [[5,12,8],[15,3,10],[2,12,7]]
OUTPUT "Enter the element to count: "
INPUT searchElement

count ← 0

// Loop through the matrix to count occurrences


FOR rowIndex ← 1 TO 3
​ FOR colIndex ← 1 TO 3
​ IF matrix[rowIndex, colIndex] = searchElement THEN
​ count ← count + 1
​ ENDIF
​ NEXT colIndex
NEXT rowIndex

OUTPUT "Element ", searchElement, " appears ", count, " times in the matrix."

40
Python
matrix = [[5, 12, 8], [15, 3, 10], [2, 12, 7]]

element = int(input("Enter the element to count: "))


count = 0

# Loop through each row


for row in range(3):
for column in range(3): # Loop through elements in the row
if matrix [row][column] == element:
count = count + 1

# Display the result


print("The element", element, "appears", count, "times in the matrix.")

41
Problem 17
Given the following arrays:

departments = ["HR", "IT", "Finance"]


employees = [
​ ["Alice", "Bob"], ​ # HR
​ ["Charlie", "David"], # IT
​ ["Eve", "Frank"] ​ # Finance
]

Write the pseudocode and Python program that takes an employee’s name and displays the department they
belong to.

pseudocode

DECLARE departments : ARRAY [1:3] OF STRING ← ["HR", "IT", "Finance"]


DECLARE employees : ARRAY [1:3, 1:2] OF STRING

employees ← [
​ ["Alice", "Bob"], // HR
​ ["Charlie", "David"], // IT
​ ["Eve", "Frank"] // Finance

DECLARE searchEmployee : STRING


DECLARE deptIndex : INTEGER
DECLARE empIndex : INTEGER
DECLARE found : BOOLEAN

OUTPUT "Enter the employee's name: "


INPUT searchEmployee

found ← FALSE

// Search for the employee in the 2D array


FOR deptIndex ← 1 TO 3
​ FOR empIndex ← 1 TO 2
​ IF employees[deptIndex, empIndex] = searchEmployee THEN
​ OUTPUT searchEmployee, " belongs to the ", departments[deptIndex], " department."
​ found ← TRUE
​ ENDIF
​ NEXT empIndex
NEXT deptIndex

// If employee not found, display message


IF found = FALSE THEN
​ OUTPUT "Employee not found."
ENDIF

42
python

Python
departments = ["HR", "IT", "Finance"]
employees = [
["Alice", "Bob"], #HR
["Charlie", "David"], #IT
["Eve", "Frank"] #Finance
]

employee_name = input("Enter employee name: ")

found = False

# Loop through each department


for i in range(len(employees)):
# Loop through each employee in the department
for j in range(len(employees[i])):
# Finds how many employees are in that department and creates a loop
that runs through each employee in that department.
if employees[i][j] == employee_name: # Compare each name
individually
print(employee_name, "belongs to the", departments[i],
"department")
found = True
break # Stop searching once found
if found:
break # Stop looping through departments

if not found:
print("Employee not found")

43
Problem 18
Given the following arrays:

students = ["Emma", "Noah", "Olivia"]


subjects = ["Math", "Science", "History"]
scores = [
​ [85, 90, 78], # Emma
​ [72, 88, 95], # Noah
​ [91, 87, 85] # Olivia
]

Write the pseudocode and Python program that displays the subjects in which a given student scored within a
specified range.

PSEUDOCODE

DECLARE students : ARRAY [1:3] OF STRING ← ["Emma", "Noah", "Olivia"]


DECLARE subjects : ARRAY [1:3] OF STRING ← ["Math", "Science", "History"]
DECLARE scores : ARRAY [1:3, 1:3] OF INTEGER

scores = [
​ [85, 90, 78], # Emma
​ [72, 88, 95], # Noah
​ [91, 87, 85] # Olivia
]

DECLARE searchStudent : STRING


DECLARE minScore : INTEGER
DECLARE maxScore : INTEGER
DECLARE studentIndex : INTEGER
DECLARE subjectIndex : INTEGER
DECLARE found : BOOLEAN

OUTPUT "Enter the student's name (Emma, Noah, Olivia): "


INPUT searchStudent

OUTPUT "Enter the minimum score: "


INPUT minScore
OUTPUT "Enter the maximum score: "
INPUT maxScore

found ← FALSE

// Search for the student index


FOR studentIndex ← 1 TO 3
​ IF students[studentIndex] = searchStudent THEN
​ OUTPUT "Subjects where ", searchStudent, " scored between ", minScore, " and ", maxScore, ":"

​ // Check each subject's score for the student


​ FOR subjectIndex ← 1 TO 3

44
​ IF scores[studentIndex, subjectIndex] >= minScore AND scores[studentIndex, subjectIndex] <=
maxScore THEN
​ OUTPUT subjects[subjectIndex]
​ found ← TRUE
​ ENDIF
​ NEXT subjectIndex
​ ENDIF
NEXT studentIndex

// If no subjects found in range, display message


IF found = FALSE THEN
​ OUTPUT "No subjects found in the specified range."
ENDIF

Python

students = ["Emma", "Noah", "Olivia"]

subjects = ["Math", "Science", "History"]

scores = [

[85, 90, 78], # Emma

[72, 88, 95], # Noah

[91, 87, 85] # Olivia

mark_range = int(input("Enter the range of marks:"))

for i in range(3):

for j in range(len(subjects)):

if scores[i][j] > mark_range:

print(students[i]," ",subjects[j]," ",scores[i][j])

45
Problem 19
Given the following arrays:
genres = ["Action", "Comedy", "Drama"]
movies = [
​ ["John Wick", "Mad Max", "Die Hard"], # Action
​ ["Superbad", "The Hangover", "Step Brothers"], # Comedy
​ ["The Godfather", "Forrest Gump", "The Shawshank Redemption"] # Drama
]

Write the pseudocode and Python program that displays the movies from the requested genre.

python

# Initialise genres and movies


genres = ["Action", "Comedy", "Drama"]
movies = [
["John Wick", "Mad Max", "Die Hard"], # Action
["Superbad", "The Hangover", "Step Brothers"], # Comedy
["The Godfather", "Forrest Gump", "The Shawshank Redemption"] # Drama
]

# Ask user for a genre


request = input("Enter a genre (Action, Comedy, Drama): ")

# Find and display the movies for that genre


found = False # Flag to check if genre exists

for i in range(len(genres)): # Loop through genre list


if request == genres[i]: # If the genre matches
print("Movies in the", request, "genre:")
for movie in movies[i]: # Loop through movies in that genre
print(movie)
found = True # Mark as found
break # Stop searching once found

# If genre not found, display message


if not found:
print("Genre not found.")

46
PSEUDOCODE

DECLARE genres : ARRAY [1:3] OF STRING ← ["Action", "Comedy", "Drama"]


DECLARE movies : ARRAY [1:3, 1:3] OF STRING

genres ← ["Action", "Comedy", "Drama"]


movies ← [
​ ["John Wick", "Mad Max", "Die Hard"],
​ ["Superbad", "The Hangover", "Step Brothers"],
​ ["The Godfather", "Forrest Gump", "The Shawshank Redemption"]]

DECLARE searchGenre : STRING


DECLARE genreIndex : INTEGER
DECLARE movieIndex : INTEGER
DECLARE found : BOOLEAN

OUTPUT "Enter the movie genre (Action, Comedy, Drama): "


INPUT searchGenre

found ← FALSE

// Search for the genre index


FOR genreIndex ← 1 TO 3
​ IF genres[genreIndex] = searchGenre THEN
​ found ← TRUE
​ OUTPUT "Movies in the ", searchGenre, " genre:"

​ // Display all movies in the found genre


​ FOR movieIndex ← 1 TO 3
​ OUTPUT movies[genreIndex, movieIndex]
​ NEXT movieIndex
​ ENDIF
NEXT genreIndex

// If genre not found, display error message


IF found = FALSE THEN
​ OUTPUT "Genre not found."
ENDIF

47

You might also like