2D Arrays Handout
2D Arrays Handout
Theory:
A two-dimensional array is an array where each element is itself an array. It is used to store data in a
table form with rows and columns.
Syntax:
datatype arrayName[rows][columns];
Special Cases:
- You must specify at least the number of columns when initializing.
- Accessing out-of-bound indices can cause unexpected results.
- 2D arrays are commonly used for matrices, tables, or grids.
Practice Examples:
Practice Example 1: Input and Display a 2D Array
#include <iostream>
using namespace std;
int main() {
int matrix[2][2];
cout << "Enter 4 numbers:" << endl;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
cin >> matrix[i][j];
}
}
cout << "Matrix is:" << endl;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Practice Example 2: Find Sum of All Elements in a 2D
Array
#include <iostream>
using namespace std;
int main() {
int matrix[2][2], sum = 0;
cout << "Enter 4 numbers:" << endl;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
cin >> matrix[i][j];
sum += matrix[i][j];
}
}
cout << "Sum of all elements: " << sum;
return 0;
}
int main() {
int matrix[2][2], transpose[2][2];
cout << "Enter 4 numbers:" << endl;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
cin >> matrix[i][j];
}
}
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
transpose[j][i] = matrix[i][j];
}
}
cout << "Transpose matrix is:" << endl;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
cout << transpose[i][j] << " ";
}
cout << endl;
}
return 0;
}
Lab Tasks:
1. Task 1: Write a program that inputs a 3x3 matrix and prints the elements present on the main
diagonal.
2. Task 2: Write a program that inputs a 3x2 matrix and calculates the sum of each column
separately.
3. Task 3: Write a program that inputs a 2x3 matrix and finds the minimum element in each row.
4. Task 4: Write a program that inputs two 3x3 matrices and multiplies them to form a third matrix.