0% found this document useful (0 votes)
3 views

2 DM Array_ new

Uploaded by

3li
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

2 DM Array_ new

Uploaded by

3li
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

‫ احمد صبيح‬.

‫د‬ Programming Fundamentals/ First Class

Dijlah College University


Department of Computer

Course 2
Multi-Dimensional Array
‫المصفوفات متعددة االبعاد‬
‫البمجة‬ ‫اساسيات ر‬
First Class
‫المرحلة االوىل‬

‫ احمد صبيح توفيق‬.‫د‬

2024-2023

1
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

Q : Write C++ program to print “ Hello World”


#include <iostream.h>
int main()
{
cout << "Hello World My name is " ;
return 0;
}
This program uses the iostream library to output the "Hello, World!" message to the console.
The std:: prefix is used to qualify elements from the standard C++ library. The main function is
the entry point of the program, and return 0; indicates successful execution.
return 0 : it return a value tells C++ program that the user has ended the program because the
program started with (int main ())
if we started with( voin main (void)) rather than (in main … return 0), the program will not
return any value
C++ Variables
● int - stores integers (whole numbers), without decimals, such as 123 or -123.
● double - stores floating point numbers, with decimals, such as 19.99 or -19.99.
● char - stores single characters, such as 'a' or 'B'. ...
● string - stores text, such as "Hello World". ...
● bool - stores values with two states: true or false.
‫ اتبع الموقع التالي‬++C ‫لمزيد من المعلومات لالطالع على لغة‬
https://www.programiz.com/cpp-programming

‫لتطبيق البرامج مباشر على شبكة االنترنت يمكن الدخول على الرابط التالي‬
https://www.programiz.com/cpp-programming/online-compiler/
‫بدل عبارة‬
#include <iostream>
‫ستكون العبارة‬
#include <iostream.h>

2
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

C++ Multidimensional Arrays

A 2D array, also known as a matrix, is a collection of elements organized in a grid-like


structure with rows and columns. It's essentially an array of arrays, where each inner
array represents a row. Here's the syntax for declaring a 2D array:
In C++, we can create an array of an array, known as a multidimensional array. For
example:

int x[3][4];

Here, x is a two-dimensional array. It can hold a maximum of 12 elements.


We can think of this array as a table with 3 rows and each row has 4 columns as shown
below.

Elements in two-dimensional
array in C++ Programming
Three-dimensional arrays also work in a similar way. For example:

float x[2][4][3];

This array x can hold a maximum of 24 elements.


We can find out the total number of elements in the array simply by multiplying its
dimensions:

3
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

2 x 4 x 3 = 24

Multidimensional Array Initialization

Like a normal array, we can initialize a multidimensional array in more than one way.

1. Initialization of two-dimensional array

int test[2][3] = {2, 4, 5, 9, 0, 19};

The above method is not preferred. A better way to initialize this array with the same
array elements is given below:

int test[2][3] = { {2, 4, 5}, {9, 0, 19}};

This array has 2 rows and 3 columns, which is why we have two rows of elements with
3 elements each.

Initializing a two-dimensional array in C++

4
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

Example 1: Two Dimensional Array: Direct Inputs


// C++ Program to display all elements
// of an initialised two dimensional array
#include <iostream>
using namespace std;
int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};
// use of nested for loop
// access rows of the array
for (int i = 0; i < 3; ++i) {
// access columns of the array
for (int j = 0; j < 2; ++j) {
cout << test[i][j] << " " ;
} cout<< endl;
}
return 0;
}

Output
2 -5
4 0
9 1
In the above example, we have initialized a two-dimensional int array
named test that has 3 "rows" and 2 "columns".
Here, we have used the nested for loop to display the array elements.
 the outer loop from i == 0 to i == 2 access the rows of the array
 the inner loop from j == 0 to j == 1 access the columns of the array
Finally, we print the array elements in each iteration.

5
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

Example 2: Taking Input from user for Two Dimensional Array

#include <iostream>
using namespace std;
int main() {
int numbers[2][3];
cout << "Enter 6 numbers: " << endl;
// Storing user input in the array

for (int i = 0; i < 2; ++i) {


for (int j = 0; j < 3; ++j) {
cin >> numbers[i][j];
}
}
cout << "The numbers are: " << endl;
// Printing array elements

for (int i = 0; i < 2; ++i) {


for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << " ";
} cout << endl;
} return 0; }
Output
Here, we have used a nested for loop to take the input of the 2d array. Once
all the input has been taken, we have used another nested for loop to print
the array members.
Enter 6 numbers:
5
1
4
4
8

6
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

5
The numbers are:
numbers[0][0]: 5 numbers[0][1]: 1 numbers[0][2]: 4
numbers[1][0]: 4 numbers[1][1]: 8 numbers[1][2]: 5

Square Matrix
A square matrix is a matrix that has an equal number of rows and columns. In mathematics, n ×
n matrix is called the square matrix of order n.
Diameters in Square Matrix When row = column: int arr[3][3]

0 1 2
0 (0,0) (0,1) (0,2)
1 (1,0) (1,1) (1,2) Main Diagonal i=j
2 (2,0) (2,1) (2,2)

0 1 2
0 (0,0) (0,1) (0,2)
1 (1,0) (1,1) (1,2) Secondary Diagonal i + j = n-1
2 (2,0) (2,1) (2,2)

0 1 2
0 (0,0) (0,1) (0,2)
1 (1,0) (1,1) (1,2)
Upper Diagonal i<j
2 (2,0) (2,1) (2,2)

0 1 2
0 (0,0) (0,1) (0,2)
1 (1,0) (1,1) (1,2) Lower Diagonal i>j
2 (2,0) (2,1) (2,2)

7
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

// Write C++ program to 1-Display the matrix arr[3][3]= {{5,15,20},{9,13,30},


{8,16,20} }; 2-Replace the main diagonal with 0. 3-Display the new matrix.
#include <iostream>
using namespace std;
int main()
{
int arr[3][3]=
{{5,15,20},
{9,13,30},
{8,16,20}
};
// Display the matrix
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
cout << "arr[" << i << "][" << j << "]: " << arr[i][j] << " ";
} cout << endl;
}
// Replace the main diagonal with 0
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if(arr[i] == arr[j]) // change the condition for H.W
arr[i][j] = 0; // change the condition for H.W
}
}
cout << endl;
// Display the new matrix
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
cout << "arr[" << i << "][" << j << "]: " << arr[i][j] << " ";
} cout << endl;
}
return 0; }
Output

8
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

H.W
Q1: Write a C++ program to perform the following operations on a square matrix 4*4:
1. Replace the main diagonal elements with the value 15.
2. Replace the secondary diagonal elements with the value 15.
3. Replace the upper diagonal elements with 16.
4. Replace the lower diagonal elements with 15.

Q2: Write a C++ program to perform the following operations on a square matrix 5*5:
1. Find the sum of the diagonal elements.
2. Find the sum of the secondary diagonal elements.
3. Find the sum of the upper diagonal elements.
4. Find the sum of the lower diagonal elements.

Types of Square Matrix


We have various types of square matrices, such as identity matrices, singular
matrices, non-singular matrices, symmetric matrices, etc.
 Scalar.
 Diagonal.
 Identity.
 Symmetric. if AT = A.

9
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

1- Scalar Matrix
A scalar matrix is a square matrix where all the off-diagonal elements (elements that are not on
the main diagonal) are zero, and the remaining diagonal elements are all equal to the same scalar
value (a single number).
 Example:
[[a, 0, 0],
[0, a, 0],
[0, 0, a]]
In this example, a is the scalar value, and all other elements are zero.
2- Diagonal Matrix
A diagonal matrix is a square matrix where all the off-diagonal elements are zero, but the
diagonal elements can have different values.
 Example:
[[1, 0, 0],
[0, 5, 0],
[0, 0, -2]]
Here, the diagonal elements are 1, 5, and -2, while all other elements are zero.
3- Identity Matrix
An identity matrix (denoted by I) is a special type of diagonal matrix where all the diagonal
elements are equal to 1.
 Example:
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
The identity matrix plays a fundamental role in linear algebra operations, similar to the number 1
in arithmetic.
4- Symmetric Matrix
A square matrix is symmetric if its elements are mirrored across the main diagonal. In other
words, for any element a<sub>ij</sub> at row i and column j, the corresponding element
a<sub>ji</sub> at row j and column i must be equal.
 Example:
[[2, 3, 1],
[3, 1, 4],
[1, 4, 5]]

10
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

In this example, notice that a<sub>12</sub> (3) is the same as a<sub>21</sub> (3),
a<sub>13</sub> (1) is the same as a<sub>31</sub> (1), and so on.
Key Points:
 All identity matrices are diagonal matrices, but not all diagonal matrices are identity
matrices (an identity matrix has specific diagonal values of 1). Scalar [] = Identity []* a.
 Symmetric matrices can be diagonal matrices, but not all diagonal matrices are
symmetric.
 a diagonal matrix is a matrix where non-zero elements only occur on the main diagonal

11
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

H.W
Write C++ program to:
1-Display the matrix arr[3][3]= {{5,15,20},{9,13,30}, {8,16,20} }.
2-Convert it to Diagonal, Print the new Matrix. (All Diagonal = Different, Other Elements = 0)
3- Convert it to Identity, Print the new Matrix. (All Diagonal = 1, Other Elements = 0)
4- Convert it to Scalar, Print the new Matrix. (Diagonal * 3, Other Elements = 0)
5- Convert it to Symmetric, Print the new Matrix. (Upper Diagonal = Lower Diagonal)
6- Transpose Matrix, Print the new Matrix. (Row becomes Column)

// Transpose the matrix


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}

Operation on Square Matrix

Operations of a Square Matrix


The mathematical operations of addition, subtraction, and multiplication can also be performed
across two square matrices. For addition or subtraction, the corresponding elements are added to
obtain the resultant matrix. Matrix addition follows commutative property (A + B = B + A).

Addition and Subtraction of Square Matrices


We can perform various mathematical operations on a square matrix, such as addition,
multiplication, etc. When two square matrices of the same order are added or subtracted, the
resultant matrix is obtained when corresponding elements are added or subtracted.
Condition: it's crucial to ensure the matrices have the same dimensions.

12
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

Q: Write C++ program to Perform


1- result [3][3] = A [3][3] + B [3][3].
2- result [3][3] = A [3][3] - B[3][3].
3- Print Error Message if the row != column.

#include <iostream>
using namespace std;

const int n = 100;

int main() {
int A[n][n], B[n][n], result[n][n];
int rowsA, colsA, rowsB, colsB;

// Input matrix A size


cout << "Enter number of rows and columns of matrix A: ";
cin >> rowsA >> colsA;

// Input elements of matrix A


cout << "Enter the elements of matrix A:" << endl;
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
cin >> A[i][j];
}
}

// Input matrix B size


cout << "Enter number of rows and columns of matrix B: ";
cin >> rowsB >> colsB;

// Input elements of matrix B


cout << "Enter the elements of matrix B:" << endl;
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
cin >> B[i][j];
}
}

// Check if matrices can be added or subtracted


if (rowsA != rowsB || colsA != colsB) {
cout << "Matrices must have the same dimensions for addition and subtraction." << endl;
return 1; // Exit with error code 1
}

// Addition of matrices A and B


13
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

cout << "Sum of matrices A and B:" << endl;


for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
result[i][j] = A[i][j] + B[i][j];
cout << result[i][j] << " ";
}
cout << endl;
}

// Subtraction of matrices B from A


cout << "Difference of matrices A and B:" << endl;
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
result[i][j] = A[i][j] - B[i][j];
cout << result[i][j] << " ";
}
cout << endl;
}

return 0;
}

14
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

Multiplication of Square Matrices


We can multiply matrices with the same dimensions directly (Hadamard product).
A=[2][2] * B[2][2]; // Correct
Direct multiplication of elements at corresponding positions in two matrices (also known as the
Hadamard product) is different from traditional matrix multiplication. In the Hadamard product,
you multiply each element of one matrix by the corresponding element of the other matrix. This
operation requires both matrices to have the same dimensions.
C[i][j] = A[i][j] * B[i][j]; // Same Idea of Addition and Subtraction

Multiplication of Matrix

To multiply two matrices 𝐴 and 𝐵, the number of columns in matrix 𝐴 must equal the number of
rows in matrix 𝐵.
If 𝐴 is of dimensions 𝑚×𝑛 and 𝐵 is of dimensions 𝑛×𝑝, the resulting matrix C will have
dimensions 𝑚×𝑝.

Condition: column of A must equal Row of B . j(A) = i(B)

C[3][3] = A [3][2] * B [2][3]

Matrix A [3][2]

|1 4|
|2 5|
|3 6|

Matrix B [2][3]

|7 8 9|
| 10 11 12 |

The resulting matrix 𝐶 will be a 3x3 matrix:


Matrix 𝐶 [3][3]

15
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

| (1*7 + 4*10) (1*8 + 4*11) (1*9 + 4*12) |


| (2*7 + 5*10) (2*8 + 5*11) (2*9 + 5*12) |
| (3*7 + 6*10) (3*8 + 6*11) (3*9 + 6*12) |

So the resulting matrix 𝐶C will be:

| 47 52 57 |
| 64 71 78 |
| 81 90 99 |

16
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

Q: Write C++ program to Perform (Direct Input)


1- C [3][3] = A [3][2] * B [2][3].
#include <iostream>
using namespace std;
int main() {
// Matrix A (3x2)
int A[3][2] = {
{1, 4},
{2, 5},
{3, 6}
};

// Matrix B (2x3)
int B[2][3] = {
{7, 8, 9},
{10, 11, 12}
};

// Resulting matrix C (3x3)


int C[3][3] = {0};

// Matrix multiplication
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
C[i][j] = 0; // Initialize C[i][j] to 0
for(int k = 0; k < 2; k++)
{
C[i][j] += A[i][k] * B[k][j];
// K is The common side between A and B (to connect them)
}
}
}

// Print the resulting matrix C


cout << "Resulting Matrix C:" << endl;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}

return 0; }

17
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

‫طريقة اخرى‬

Q: Write C++ program to Perform the matrices A and B, (use user


input).
#include <iostream>
using namespace std;

const int n = 100;

int main() {
int A[n][n], B[n][n], result[n][n];
int rowsA, colsA, rowsB, colsB;

// Input size of matrix A


cout << "Enter number of rows and columns of matrix A: ";
cin >> rowsA >> colsA;

// Input elements of matrix A


cout << "Enter the elements of matrix A:" << endl;
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
cin >> A[i][j];
}
}

// Input size of matrix B


cout << "Enter number of rows and columns of matrix B: ";
cin >> rowsB >> colsB;

// Input elements of matrix B


cout << "Enter the elements of matrix B:" << endl;
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
cin >> B[i][j];
}
}

// Check if matrices can be multiplied


if (colsA != rowsB) {
cout << "Matrices cannot be multiplied due to incompatible dimensions." << endl;
return 1; // Exit with error code 1
}

// Perform matrix multiplication


18
‫ احمد صبيح‬.‫د‬ Programming Fundamentals/ First Class

for (int i = 0; i < rowsA; i++) {


for (int j = 0; j < colsB; j++) {
result[i][j] = 0;
for (int k = 0; k < colsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}

// Display the result matrix


cout << "Result of matrix multiplication:" << endl;
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}

return 0;
}

19

You might also like