2D Arrays Problems and Solutions
2D Arrays Problems and Solutions
1
Pseudocode for known set of data
twoDarray ← [[1,2,3]
[4,5,6]
[7,8,9]]
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
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
grid = [ ]
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:
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
6
Pseudocode
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]]
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:
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
array = [
[1, 2, 3, 4],
[5, 6, 7, 8],
# Initialize total
total = 0
for i in range(4):
for j in range(4):
for i in range(4):
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
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
array = []
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()
print("\n")
13
for i in range(row):
row_sum = 0
for j in range(column):
print("\n")
for j in range(column):
col_sum = 0
for i in range(row):
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.
10 4 9
7 2 5
1 8 3
Output array:
0 0 0
0 0 0
0 0 0
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
array = []
for i in range(rows):
temp = []
for j in range(columns):
temp.append(num)
array.append(temp)
print("\n")
for i in range(rows):
for j in range(columns):
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()
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.
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
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
19
Python:
Python
# Initialize counters
count_over_five = 0
count_under_five = 0
grid = []
for i in range(rows):
for k in range(columns):
print("\nGrid:")
for i in range(rows):
for k in range(columns):
20
print() # Move to the next line after each row
for i in range(rows):
for k in range(columns):
if grid[i][k] >= 5:
count_over_five += 1
else:
count_under_five += 1
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.
10 14 19
7 21 5
1 8 3
Output:
10 19 21 1 3
Pseudocode
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 = []
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).
Names
Alan Kacie Jake Ivy
Marks
90 89 78
85 83 82
65 67 68
87 79 80
24
Pseudocode
// Display
OUTPUT ("Marks of students: ")
OUTPUT ("Name Assessment 1 Assessment 2 Assessment 3")
// Calculate average
Highest_average ← -1
Top_student ← “ “
OUTPUT ("Student with the highest average marks: ", top_student, " with an average of ",
highest_average)
25
Python
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
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]
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:
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
27
Python
array = []
for i in range(rows):
temp = []
for j in range(columns):
temp.append(num)
array.append(temp)
for i in range(rows):
for j in range(columns):
print()
max_num = array[0][0]
for i in range(rows):
for j in range(columns):
max_num = array[i][j]
28
Problem 11
Write the pseudocode and Python program that finds the salary of the given employee’s name.
Pseudocode:
29
Python
for x in range(3):
if employee == employees[x]:
print(salaries[x])
if not found:
30
Problem 12
Given:
Write the pseudocode and Python to find the city with the highest temperature.
Pseudocode
// Initialize maxTemp with the first temperature and maxCity with the first city
maxTemp ← temperatures[1]
maxCity ← cities[1]
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]
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
Sample output:
PYTHON
33
PSEUDOCODE - FOR Loop
found ← FALSE
34
PSEUDOCODE - While Loop
matrix ← [
[5, 12, 8],
[15, 3, 10],
[2, 18, 7]
]
found ← FALSE
rowIndex ← 1
rowIndex ← rowIndex + 1
ENDWHILE
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
36
PSEUDOCODE
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
38
PSEUDOCODE
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
Sample output:
count ← 0
OUTPUT "Element ", searchElement, " appears ", count, " times in the matrix."
40
Python
matrix = [[5, 12, 8], [15, 3, 10], [2, 12, 7]]
41
Problem 17
Given the following arrays:
Write the pseudocode and Python program that takes an employee’s name and displays the department they
belong to.
pseudocode
employees ← [
["Alice", "Bob"], // HR
["Charlie", "David"], // IT
["Eve", "Frank"] // Finance
found ← FALSE
42
python
Python
departments = ["HR", "IT", "Finance"]
employees = [
["Alice", "Bob"], #HR
["Charlie", "David"], #IT
["Eve", "Frank"] #Finance
]
found = False
if not found:
print("Employee not found")
43
Problem 18
Given the following arrays:
Write the pseudocode and Python program that displays the subjects in which a given student scored within a
specified range.
PSEUDOCODE
scores = [
[85, 90, 78], # Emma
[72, 88, 95], # Noah
[91, 87, 85] # Olivia
]
found ← FALSE
44
IF scores[studentIndex, subjectIndex] >= minScore AND scores[studentIndex, subjectIndex] <=
maxScore THEN
OUTPUT subjects[subjectIndex]
found ← TRUE
ENDIF
NEXT subjectIndex
ENDIF
NEXT studentIndex
Python
scores = [
for i in range(3):
for j in range(len(subjects)):
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
46
PSEUDOCODE
found ← FALSE
47