Initializing a 2D matrix and accessing, modifying Elements in it
In this article we will go through code examples in different languages to create and initialize a 2 dimensional matrix and to access/modify individual elements.
Consider a use-case where there are 4 students in a class and we need to store marks obtained by each student in 3 different subjects. In order to achieve this, we create a 2-dimensional array with 4 rows and 3 columns, Each row contains marks in all the subjects obtained by the student.
[
[81, 75, 92], // Student-0's marks
[86, 94, 79], // Student-1's marks
[84, 90, 75], // Student-2's marks
[79, 75, 89] // Student-3's marks
]
The first row in the above 2D array/matrix corresponds to marks obtained in 3 different subjects by student-0.Similarly the second row corresponds to marks obtained by 3 different subjects by student-1 and so on.
Similarly for each of the students marks, the first element corresponds to marks obtained in subject-0, the second element corresponds marks obtained in subject-1 and so on.
Initializing, Accessing, Modifying elements in 2D Array
Let’s look at code in different languages which does the below:
Initialize a multi-dimensional array containing marks of all the students in all the subjects.
Print marks obtained by student-2 in each of the subjects.
Modify marks obtained by Student-2 in subject-1 to 88
# Declare and initialize a 2D list (4x3 matrix) representing student marks
student_marks = [
[81, 75, 92], # Student-0's marks
[86, 94, 79], # Student-1's marks
[84, 90, 75], # Student-2's marks
[79, 75, 89] # Student-3's marks
]
# Access and print the marks of a specific student (e.g., student-2)
student_id = 2
print(f"Printing Marks for Student {student_id}:")
print(f"Subject 1: {student_marks[student_id][0]}")
print(f"Subject 2: {student_marks[student_id][1]}")
print(f"Subject 3: {student_marks[student_id][2]}")
# Modify a student's mark
# e.g., change marks of Student-2 for subject with id 1 to 88
student_id = 2
subject_id = 1
new_mark = 88
student_marks[student_id][subject_id] = new_mark
# Access and print the modified mark
print(f"Modified mark for Student 2 in Subject 1 to {student_marks[student_id][subject_id]}")
#include <stdio.h>
int main() {
// Declare and initialize a 2D array (4x3 matrix) representing student marks
int student_marks[4][3] = {
{81, 75, 92}, // Student-0's marks
{86, 94, 79}, // Student-1's marks
{84, 90, 75}, // Student-2's marks
{79, 75, 89} // Student-3's marks
};
// Access and print the marks of a specific student (e.g., student-2)
int student_id = 2;
printf("Printing Marks for Student %d:\n", student_id);
printf("Subject 1: %d\n", student_marks[student_id][0]);
printf("Subject 2: %d\n", student_marks[student_id][1]);
printf("Subject 3: %d\n", student_marks[student_id][2]);
// Modify a student's mark
// e.g., change marks of Student-2 for subject with id 1 to 88
student_id = 2;
int subject_id = 1, new_mark = 88;
student_marks[student_id][subject_id] = new_mark;
// Access and print the modified mark
printf("Modified mark for Student 2 in Subject 1 to %d\n", student_marks[student_id][subject_id]);
return 0;
}
#include <iostream>
#include <vector>
int main() {
// Declare and initialize a 2D vector (4x3 matrix) representing student marks
std::vector<std::vector<int>> student_marks = {
{81, 75, 92}, // Student-0's marks
{86, 94, 79}, // Student-1's marks
{84, 90, 75}, // Student-2's marks
{79, 75, 89} // Student-3's marks
};
// Access and print the marks of a specific student (e.g., student-2)
int student_id = 2;
std::cout << "Printing Marks for Student " << student_id << ":" << std::endl;
std::cout << "Subject 1: " << student_marks[student_id][0] << std::endl;
std::cout << "Subject 2: " << student_marks[student_id][1] << std::endl;
std::cout << "Subject 3: " << student_marks[student_id][2] << std::endl;
// Modify a student's mark
// e.g., change marks of Student-2 for subject with id 1 to 88
student_id = 2;
int subject_id = 1;
int new_mark = 88;
student_marks[student_id][subject_id] = new_mark;
// Access and print the modified mark
std::cout << "Modified mark for Student 2 in Subject 1 to " << student_marks[student_id][subject_id] << std::endl;
return 0;
}
// Declare and initialize a 2D array (4x3 matrix) representing student marks
const student_marks = [
[81, 75, 92], // Student-0's marks
[86, 94, 79], // Student-1's marks
[84, 90, 75], // Student-2's marks
[79, 75, 89] // Student-3's marks
];
// Access and print the marks of a specific student (e.g., student-2)
let student_id = 2;
console.log(`Printing Marks for Student ${student_id}:`);
console.log(`Subject 1: ${student_marks[student_id][0]}`);
console.log(`Subject 2: ${student_marks[student_id][1]}`);
console.log(`Subject 3: ${student_marks[student_id][2]}`);
// Modify a student's mark
// e.g., change marks of Student-2 for subject with id 1 to 88
student_id = 2;
let subject_id = 1;
let new_mark = 88;
student_marks[student_id][subject_id] = new_mark;
// Access and print the modified mark
console.log(`Modified mark for Student 2 in Subject 1 to ${student_marks[student_id][subject_id]}`);
public class Main {
public static void main(String[] args) {
// Declare and initialize a 2D array (4x3 matrix) representing student marks
int[][] studentMarks = {
{81, 75, 92}, // Student-0's marks
{86, 94, 79}, // Student-1's marks
{84, 90, 75}, // Student-2's marks
{79, 75, 89} // Student-3's marks
};
// Access and print the marks of a specific student (e.g., student-2)
int studentId = 2;
System.out.println("Printing Marks for Student " + studentId + ":");
System.out.println("Subject 1: " + studentMarks[studentId][0]);
System.out.println("Subject 2: " + studentMarks[studentId][1]);
System.out.println("Subject 3: " + studentMarks[studentId][2]);
// Modify a student's mark
// e.g., change marks of Student-2 for subject with id 1 to 88
studentId = 2;
int subjectId = 1;
int newMark = 88;
studentMarks[studentId][subjectId] = newMark;
// Access and print the modified mark
System.out.println("Modified mark for Student 2 in Subject 1 to " + studentMarks[studentId][subjectId]);
}
}
If you wish to access marks in subject-1 for student-3, you need to use an expression like student_marks[3][1] to get the marks. You can also use a similar expression to set a specific value: student_marks[3][1] = 92.
Initializing and Filling a 2D array from terminal input
In the previous section, we looked at a scenario where all the values of 2D array are known beforehand and so the 2D array is directly created in code with exact values. But in most of the scenarios, the creation of 2D array will be dynamic and has to be done at runtime based on the number of rows, columns and values provided as input by the user.
The code below helps achieving that by asking the user the number of rows (number of students) and columns (number of subjects) the 2D array should have. It then initializes and resizes the array if required and asks user to fill in contents present in each row until all the rows are filled.
# Declare variables to store number of rows and columns
num_rows, num_cols = 0, 0
# Declare 2D array to store student marks
student_marks = []
# Get number of students
print("Enter the number of students: ")
num_rows = int(input())
# Get number of subjects
print("Enter the number of subjects: ")
num_cols = int(input())
# Initialize the array
for i in range(num_rows):
print(f"Filling marks in all subjects for student {i}")
row = []
for j in range(num_cols):
print(f"Enter marks for student {i} in subject {j}: ")
marks = int(input())
row.append(marks)
student_marks.append(row)
print(f"Done filling marks in all subjects for student {i}")
#include <stdio.h>
#include <stdlib.h>
int main() {
// Declare variables to store number of rows and columns
int num_rows, num_cols;
// Declare 2D array to store student marks
int** student_marks;
// Get number of students
printf("Enter the number of students: ");
scanf("%d", &num_rows);
// Get number of subjects
printf("Enter the number of subjects: ");
scanf("%d", &num_cols);
// Initialize the array
student_marks = (int**)malloc(num_rows * sizeof(int*));
for (int i = 0; i < num_rows; i++) {
student_marks[i] = (int*)malloc(num_cols * sizeof(int));
}
for (int i = 0; i < num_rows; i++) {
printf("Filling marks in all subjects for student %d\n", i);
for (int j = 0; j < num_cols; j++) {
printf("Enter marks for student %d in subject %d: ", i, j);
scanf("%d", &student_marks[i][j]);
}
printf("Done filling marks in all subjects for student %d\n", i);
}
// Free the dynamically allocated memory
for (int i = 0; i < num_rows; i++) {
free(student_marks[i]);
}
free(student_marks);
return 0;
}
#include <iostream>
#include <vector>
int main() {
// Declare variables to store number of rows and columns
int num_rows, num_cols;
// Declare 2D array to store student marks
std::vector<std::vector<int>> student_marks;
// Get number of students
std::cout << "Enter the number of students: ";
std::cin >> num_rows;
// Get number of subjects
std::cout << "Enter the number of subjects: ";
std::cin >> num_cols;
// Initialize the array
for (int i = 0; i < num_rows; i++) {
std::cout << "Filling marks in all subjects for student " << i << std::endl;
std::vector<int> row(num_cols);
for (int j = 0; j < num_cols; j++) {
std::cout << "Enter marks for student " << i << " in subject " << j << ": ";
std::cin >> row[j];
}
student_marks.push_back(row);
std::cout << "Done filling marks in all subjects for student " << i << std::endl;
}
return 0;
}
// Declare variables to store number of rows and columns
let num_rows, num_cols;
// Declare 2D array to store student marks
let student_marks = [];
// Get number of students
console.log("Enter the number of students: ");
num_rows = parseInt(readline());
// Get number of subjects
console.log("Enter the number of subjects: ");
num_cols = parseInt(readline());
// Initialize the array
for (let i = 0; i < num_rows; i++) {
console.log("Filling marks in all subjects for student ", i);
student_marks[i] = [];
for (let j = 0; j < num_cols; j++) {
console.log("Enter marks for student ", i, " in subject ", j, ": ");
student_marks[i][j] = parseInt(readline());
}
console.log("Done filling marks in all subjects for student ", i);
}
// Declare variables to store number of rows and columns
int num_rows, num_cols;
// Declare 2D array to store student marks
int[][] student_marks;
// Get number of students
System.out.print("Enter the number of students: ");
num_rows = Integer.parseInt(System.console().readLine());
// Get number of subjects
System.out.print("Enter the number of subjects: ");
num_cols = Integer.parseInt(System.console().readLine());
// Initialize the array
student_marks = new int[num_rows][num_cols];
for (int i = 0; i < num_rows; i++) {
System.out.println("Filling marks in all subjects for student " + i);
for (int j = 0; j < num_cols; j++) {
System.out.print("Enter marks for student " + i + " in subject " + j + ": ");
student_marks[i][j] = Integer.parseInt(System.console().readLine());
}
System.out.println("Done filling marks in all subjects for student " + i);
}
In the next section we will go through how to traverse elements in a 2D array in different variations.