C++ Program to Interchange Elements of First and Last Columns in Matrix

Interchanging elements of the first and last columns of a matrix involves swapping the elements of the first column with the corresponding elements of the last column.

Problem Statement

Given a matrix, interchange the elements of the first column with those of the last column.

Approach

  1. Initialization: Verify the matrix is valid (non-empty and has more than one column).
  2. Swapping Elements: Iterate through each row of the matrix and swap the elements of the first column with the corresponding elements of the last column.

Example

For a 3×3 matrix:

Matrix before interchange:

1 2 3

4 5 6

7 8 9

Matrix after interchange:

3 2 1

6 5 4

9 8 7

C++ Code Implementation

Here is a C++ program to interchange the elements of the first and last columns of a matrix:

#include <iostream>

#include <vector>

using namespace std;

// Function to interchange elements of the first and last columns of a matrix

void interchangeFirstLastColumns(vector<vector<int>>& matrix) {

    int numRows = matrix.size();

    int numCols = matrix[0].size();

   

    if (numCols < 2) {

        cout << “Matrix must have at least two columns to interchange.” << endl;

        return;

    }

    for (int row = 0; row < numRows; ++row) {

        swap(matrix[row][0], matrix[row][numCols – 1]);

    }

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing a 3×3 matrix

    vector<vector<int>> matrix = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    cout << “Matrix before interchange:” << endl;

    printMatrix(matrix);

    // Interchanging the first and last columns

    interchangeFirstLastColumns(matrix);

    cout << “Matrix after interchange:” << endl;

    printMatrix(matrix);

    return 0;

}

Explanation

  1. Function interchangeFirstLastColumns:

  • Parameters: Takes a 2D vector (matrix).
  • Validation: Checks if the matrix has at least two columns. If not, it outputs a message and returns.
  • Swapping Elements: Uses a loop to iterate through each row, swapping the elements of the first column with the corresponding elements of the last column.
  1. Function printMatrix:

  • Parameters: Takes a 2D vector (matrix).
  • Printing: Iterates through the matrix and prints its elements in a formatted manner for better visualization.
  1. Main Function:

  • Matrix Initialization: Creates a sample 3×3 matrix.
  • Printing Before Interchange: Prints the matrix before interchanging the columns.
  • Column Interchange: Calls the interchangeFirstLastColumns function to swap the first and last columns.
  • Printing After Interchange: Prints the matrix after interchanging the columns.

C++ Program to Interchange Elements of First and Last Rows in Matrix

Interchanging elements of the first and last rows of a matrix involves swapping the elements of the first row with the corresponding elements of the last row.

Problem Statement

Given a matrix, interchange the elements of the first row with those of the last row.

Approach

  1. Initialization: Verify the matrix is valid (non-empty and has more than one row).
  2. Swapping Elements: Iterate through each column of the matrix and swap the elements of the first row with the corresponding elements of the last row.

Example

For a 3×3 matrix:

Matrix before interchange:

1 2 3

4 5 6

7 8 9

Matrix after interchange:

7 8 9

4 5 6

1 2 3

C++ Code Implementation

Here is a C++ program to interchange the elements of the first and last rows of a matrix:

#include <iostream>

#include <vector>

using namespace std;

// Function to interchange elements of the first and last rows of a matrix

void interchangeFirstLastRows(vector<vector<int>>& matrix) {

    int numRows = matrix.size();

    if (numRows < 2) {

        cout << “Matrix must have at least two rows to interchange.” << endl;

        return;

    }

    int numCols = matrix[0].size();

    for (int col = 0; col < numCols; ++col) {

        swap(matrix[0][col], matrix[numRows – 1][col]);

    }

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing a 3×3 matrix

    vector<vector<int>> matrix = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    cout << “Matrix before interchange:” << endl;

    printMatrix(matrix);

    // Interchanging the first and last rows

    interchangeFirstLastRows(matrix);

    cout << “Matrix after interchange:” << endl;

    printMatrix(matrix);

    return 0;

}

Explanation

  1. Function interchangeFirstLastRows:

  • Parameters: Takes a 2D vector (matrix).
  • Validation: Checks if the matrix has at least two rows. If not, it outputs a message and returns.
  • Swapping Elements: Uses a loop to iterate through each column, swapping the elements of the first row with the corresponding elements of the last row.
  1. Function printMatrix:

  • Parameters: Takes a 2D vector (matrix).
  • Printing: Iterates through the matrix and prints its elements in a formatted manner for better visualization.
  1. Main Function:

  • Matrix Initialization: Creates a sample 3×3 matrix.
  • Printing Before Interchange: Prints the matrix before interchanging the rows.
  • Row Interchange: Calls the interchangeFirstLastRows function to swap the first and last rows.
  • Printing After Interchange: Prints the matrix after interchanging the rows.

C++ Program to Multiply Two Matrices

Multiplying two matrices involves computing the dot product of rows from the first matrix with columns of the second matrix to get the elements of the resulting matrix.

Problem Statement

Given two matrices, compute their product. The number of columns in the first matrix must be equal to the number of rows in the second matrix for the multiplication to be defined.

Approach

  • Initialization:

Create a result matrix with dimensions corresponding to the number of rows of the first matrix and the number of columns of the second matrix.

  • Multiplication:

For each element in the result matrix, compute the sum of the products of corresponding elements from the rows of the first matrix and columns of the second matrix.

Example

For two matrices:

Matrix A:

1 2

3 4

5 6

Matrix B:

7  8  9

10 11 12

The resulting matrix C will be:

Matrix C:

(1*7 + 2*10)  (1*8 + 2*11)  (1*9 + 2*12)

(3*7 + 4*10)  (3*8 + 4*11)  (3*9 + 4*12)

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

Matrix C:

27  30  33

61  68  75

95  106 117

C++ Code Implementation

Here’s a C++ program to multiply two matrices:

#include <iostream>

#include <vector>

using namespace std;

// Function to multiply two matrices

vector<vector<int>> multiplyMatrices(const vector<vector<int>>& mat1, const vector<vector<int>>& mat2) {

    int rows1 = mat1.size();

    int cols1 = mat1[0].size();

    int cols2 = mat2[0].size();

   

    // Initialize result matrix with zeroes

    vector<vector<int>> result(rows1, vector<int>(cols2, 0));

   

    // Matrix multiplication

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

        for (int j = 0; j < cols2; ++j) {

            for (int k = 0; k < cols1; ++k) {

                result[i][j] += mat1[i][k] * mat2[k][j];

            }

        }

    }

   

    return result;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing two matrices

    vector<vector<int>> mat1 = {

        {1, 2},

        {3, 4},

        {5, 6}

    };

    vector<vector<int>> mat2 = {

        {7,  8,  9},

        {10, 11, 12}

    };

    cout << “Matrix A:” << endl;

    printMatrix(mat1);

    cout << “Matrix B:” << endl;

    printMatrix(mat2);

    // Multiplying the matrices

    vector<vector<int>> result = multiplyMatrices(mat1, mat2);

    cout << “Resultant Matrix (A * B):” << endl;

    printMatrix(result);

    return 0;

}

Explanation

  1. Function multiplyMatrices:

    • Parameters: Takes two 2D vectors (mat1 and mat2).
    • Initialization: Creates a result matrix filled with zeros, with dimensions (rows1, cols2), where rows1 is the number of rows in mat1 and cols2 is the number of columns in mat2.
    • Matrix Multiplication: Nested loops are used to iterate through the elements of the matrices and compute the dot products for the resulting matrix.
    • Return Value: Returns the resulting matrix after multiplication.
  2. Function printMatrix:

    • Prints the matrix in a formatted way for better visualization.
  3. Main Function:

    • Initializes two sample matrices.
    • Prints the matrices.
    • Calls the multiplyMatrices function to multiply the two matrices.
    • Prints the resulting matrix.

C++ Program to Find the Normal and Trace of Matrix

To find the normal and trace of a matrix, we need to understand the definitions of these terms:

  1. Trace of a Matrix: The trace of a square matrix is the sum of the elements on its main diagonal (from the upper left to the lower right).
  2. Normal of a Matrix: The normal (or Frobenius norm) of a matrix is the square root of the sum of the squares of all its elements.

Problem Statement

Given a square matrix, compute its trace and normal.

Approach

  1. Trace Calculation: Sum the diagonal elements of the matrix.
  2. Normal Calculation: Compute the sum of the squares of all elements in the matrix, then take the square root of this sum.

Example

For a 3×3 matrix:

Matrix:

1 2 3

4 5 6

7 8 9

  • Trace: 1+5+9=15
  • Normal: √{1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 9^2} = √285​ ≈ 16.88

C++ Code Implementation

Here is a C++ program to compute the trace and normal of a matrix:

#include <iostream>

#include <vector>

#include <cmath>

using namespace std;

// Function to compute the trace of a matrix

int traceOfMatrix(const vector<vector<int>>& matrix) {

    int trace = 0;

    for (size_t i = 0; i < matrix.size(); ++i) {

        trace += matrix[i][i];

    }

    return trace;

}

// Function to compute the normal (Frobenius norm) of a matrix

double normalOfMatrix(const vector<vector<int>>& matrix) {

    double sumOfSquares = 0.0;

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            sumOfSquares += elem * elem;

        }

    }

    return sqrt(sumOfSquares);

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing a 3×3 matrix

    vector<vector<int>> matrix = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    cout << “Matrix:” << endl;

    printMatrix(matrix);

    // Computing the trace of the matrix

    int trace = traceOfMatrix(matrix);

    cout << “Trace of the matrix: ” << trace << endl;

    // Computing the normal of the matrix

    double normal = normalOfMatrix(matrix);

    cout << “Normal (Frobenius norm) of the matrix: ” << normal << endl;

    return 0;

}

Explanation

  1. Function traceOfMatrix:
  • Parameters: Takes a 2D vector (matrix).
  • Trace Calculation: Iterates through the diagonal elements (where row index equals column index) and sums them.
  • Return Value: Returns the computed trace.
  1. Function normalOfMatrix:
  • Parameters: Takes a 2D vector (matrix).
  • Normal Calculation: Iterates through all elements of the matrix, calculates the sum of their squares, and returns the square root of this sum.
  • Return Value: Returns the computed normal.
  1. Function printMatrix:

Prints the matrix in a formatted way for better visualization.

  1. Main Function:

  • Initializes a sample 3×3 matrix.
  • Prints the matrix.
  • Calls the traceOfMatrix function to compute the trace and prints it.
  • Calls the normalOfMatrix function to compute the normal and prints it.

C++ Program to Find the Transpose of a Matrix

Finding the transpose of a matrix involves swapping its rows with its columns. In other words, the element at position (i, j) in the original matrix moves to position (j, i) in the transposed matrix.

Problem Statement

Given a matrix, compute its transpose. The transpose of a matrix is obtained by swapping rows with columns.

Approach

  1. Initialize a Transposed Matrix:

Create a new matrix to store the transposed values, which will have dimensions swapped compared to the original matrix.

  1. Swap Elements:

Iterate through each element of the original matrix, and assign it to the transposed matrix by swapping the row and column indices.

Example

For a 3×3 matrix:

Original Matrix:

1 2 3

4 5 6

7 8 9

Transposed Matrix:

1 4 7

2 5 8

3 6 9

C++ Code Implementation

Here is a C++ program to compute the transpose of a matrix:

#include <iostream>

#include <vector>

using namespace std;

// Function to compute the transpose of a matrix

vector<vector<int>> transposeMatrix(const vector<vector<int>>& matrix) {

    int rows = matrix.size();

    int cols = matrix[0].size();

    vector<vector<int>> transposedMatrix(cols, vector<int>(rows));

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

        for (int j = 0; j < cols; ++j) {

            transposedMatrix[j][i] = matrix[i][j];

        }

    }

    return transposedMatrix;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing a 3×3 matrix

    vector<vector<int>> matrix = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    cout << “Original Matrix:” << endl;

    printMatrix(matrix);

    // Computing the transpose of the matrix

    vector<vector<int>> transposedMatrix = transposeMatrix(matrix);

    cout << “Transposed Matrix:” << endl;

    printMatrix(transposedMatrix);

    return 0;

}

Explanation

  1. Function transposeMatrix:

  • Parameters:

Takes a 2D vector (matrix).

  • Initialization:

Creates a new matrix (transposedMatrix) with swapped dimensions (number of rows becomes number of columns and vice versa).

  • Element Swapping:

Iterates through each element of the original matrix and assigns it to the corresponding position in the transposed matrix by swapping the indices.

  • Return Value:

Returns the transposed matrix.

  1. Function printMatrix:

Prints the matrix in a formatted way for better visualization.

  1. Main Function:

  • Initializes a sample 3×3 matrix.
  • Prints the original matrix.
  • Calls the transposeMatrix function to compute the transpose.
  • Prints the transposed matrix.

C++ Program to Print Boundary Elements of a Matrix

To print the boundary elements of a matrix, we need to identify and print elements that lie on the outermost edges of the matrix. These elements include the elements in the first and last rows, and the elements in the first and last columns, excluding the corners already included in the first and last rows.

Problem Statement

Given a matrix, print its boundary elements. The boundary elements include:

  • All elements in the first row.
  • All elements in the last row.
  • All elements in the first column (excluding the first and last elements if already included).
  • All elements in the last column (excluding the first and last elements if already included).

Approach

  1. First Row: Print all elements in the first row.
  2. Last Column: Print all elements in the last column, excluding the first and last elements.
  3. Last Row: Print all elements in the last row, in reverse order, excluding the last element (already printed).
  4. First Column: Print all elements in the first column, in reverse order, excluding the first and last elements.

Example

For a 4×4 matrix:

1  2  3  4

5  6  7  8

9  10 11 12

13 14 15 16

The boundary elements are:

1 2 3 4 8 12 16 15 14 13 9 5

C++ Code Implementation

Here is a C++ program to print the boundary elements of a matrix:

#include <iostream>

#include <vector>

using namespace std;

// Function to print the boundary elements of a matrix

void printBoundaryElements(const vector<vector<int>>& matrix) {

    int rows = matrix.size();

    int cols = matrix[0].size();

    if (rows == 1) {

        // Special case: single row matrix

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

            cout << matrix[0][i] << ” “;

        }

    } else if (cols == 1) {

        // Special case: single column matrix

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

            cout << matrix[i][0] << ” “;

        }

    } else {

        // Print the first row

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

            cout << matrix[0][i] << ” “;

        }

        // Print the last column

        for (int i = 1; i < rows – 1; ++i) {

            cout << matrix[i][cols – 1] << ” “;

        }

        // Print the last row

        for (int i = cols – 1; i >= 0; –i) {

            cout << matrix[rows – 1][i] << ” “;

        }

        // Print the first column

        for (int i = rows – 2; i > 0; –i) {

            cout << matrix[i][0] << ” “;

        }

    }

    cout << endl;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing a 4×4 matrix

    vector<vector<int>> matrix = {

        {1, 2, 3, 4},

        {5, 6, 7, 8},

        {9, 10, 11, 12},

        {13, 14, 15, 16}

    };

    cout << “Matrix:” << endl;

    printMatrix(matrix);

    // Printing the boundary elements of the matrix

    cout << “Boundary Elements:” << endl;

    printBoundaryElements(matrix);

    return 0;

}

Explanation

  1. Function printBoundaryElements:

    • Parameters: Takes a 2D vector (matrix).
    • Single Row Matrix: Handles the special case where the matrix has only one row by printing all elements in that row.
    • Single Column Matrix: Handles the special case where the matrix has only one column by printing all elements in that column.
    • General Case:
      • Prints all elements in the first row.
      • Prints all elements in the last column, except the first and last elements.
      • Prints all elements in the last row in reverse order, except the last element.
      • Prints all elements in the first column in reverse order, except the first and last elements.
  1. Function printMatrix:

    • Prints the matrix in a formatted manner for better visualization.
  2. Main Function:

    • Initializes a sample 4×4 matrix.
    • Prints the matrix.
    • Calls the printBoundaryElements function to print the boundary elements.
    • Outputs the boundary elements of the matrix.

C++ Program to Compute the Sum of Diagonals of a Matrix

To compute the sum of the diagonals of a matrix, we need to consider both the primary (main) diagonal and the secondary (anti) diagonal. The primary diagonal consists of elements where the row index is equal to the column index. The secondary diagonal consists of elements where the sum of the row index and column index is equal to the size of the matrix minus one.

Problem Statement

Given a square matrix, compute the sum of its primary and secondary diagonals.

Approach

  1. Primary Diagonal: Sum elements where the row index equals the column index.
  2. Secondary Diagonal: Sum elements where the sum of the row and column indices equals the size of the matrix minus one.
  3. Avoid Double Counting: If the matrix size is odd, the central element will be counted twice. Adjust the sum to subtract the central element once in this case.

Example

For a 3×3 matrix:

1 2 3

4 5 6

7 8 9

Primary diagonal sum: 1+5+9=15

Secondary diagonal sum: 3+5+7=15

Total sum of diagonals: 15+15−5=25 (Subtract the central element 5 once because it’s counted twice).

C++ Code Implementation

Here is the C++ program to compute the sum of the diagonals of a matrix:

#include <iostream>

#include <vector>

using namespace std;

// Function to compute the sum of the diagonals of a matrix

int sumOfDiagonals(const vector<vector<int>>& matrix) {

    int n = matrix.size();

    int primaryDiagonalSum = 0;

    int secondaryDiagonalSum = 0;

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

        primaryDiagonalSum += matrix[i][i];

        secondaryDiagonalSum += matrix[i][n – 1 – i];

    }

    int totalDiagonalSum = primaryDiagonalSum + secondaryDiagonalSum;

    // If the matrix has an odd size, subtract the central element which is counted twice

    if (n % 2 == 1) {

        totalDiagonalSum -= matrix[n / 2][n / 2];

    }

    return totalDiagonalSum;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing a 3×3 matrix

    vector<vector<int>> matrix = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    cout << “Matrix:” << endl;

    printMatrix(matrix);

    // Computing the sum of the diagonals

    int diagonalSum = sumOfDiagonals(matrix);

    cout << “Sum of the diagonals: ” << diagonalSum << endl;

    return 0;

}

Explanation

  1. Function sumOfDiagonals:

  • Parameters: Takes a 2D vector (matrix).
  • Primary Diagonal Sum: Sums elements where the row index equals the column index.
  • Secondary Diagonal Sum: Sums elements where the sum of the row index and column index equals n−1n – 1n−1.
  • Total Sum Calculation: Sums the primary and secondary diagonal sums.
  • Adjustment for Odd-sized Matrix: Subtracts the central element once if the matrix size is odd, to avoid double counting.
  • Return Value: Returns the total diagonal sum.
  1. Function printMatrix:

Prints the matrix in a formatted way for better visualization.

  1. Main Function:
  • Initializes a sample 3×3 matrix.
  • Prints the matrix.
  • Calls the sumOfDiagonals function to compute the sum of the diagonals.
  • Outputs the result of the diagonal sum.

C++ Program to Check Whether Two Matrices Are Equal or Not

To check whether two matrices are equal, we need to verify that they have the same dimensions and that each corresponding element is identical.

Problem Statement

Given two matrices, determine if they are equal. Two matrices are considered equal if they have the same dimensions and their corresponding elements are identical.

Approach

  1. Dimension Check: First, ensure that both matrices have the same number of rows and columns.
  2. Element-wise Comparison: Compare each corresponding element in the two matrices. If all corresponding elements are equal, the matrices are considered equal; otherwise, they are not.

Example

Given two 3×3 matrices:

Matrix A:

1 2 3

4 5 6

7 8 9

Matrix B:

1 2 3

4 5 6

7 8 9

These matrices are equal.

Given another pair of matrices:

Matrix A:

1 2 3

4 5 6

7 8 9

Matrix B:

9 8 7

6 5 4

3 2 1

These matrices are not equal.

C++ Code Implementation

Here is a C++ program to check whether two matrices are equal:

#include <iostream>

#include <vector>

using namespace std;

// Function to check if two matrices are equal

bool areMatricesEqual(const vector<vector<int>>& matrixA, const vector<vector<int>>& matrixB) {

    if (matrixA.size() != matrixB.size() || matrixA[0].size() != matrixB[0].size()) {

        return false;

    }

    for (size_t i = 0; i < matrixA.size(); ++i) {

        for (size_t j = 0; j < matrixA[0].size(); ++j) {

            if (matrixA[i][j] != matrixB[i][j]) {

                return false;

            }

        }

    }

    return true;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing two 3×3 matrices

    vector<vector<int>> matrixA = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    vector<vector<int>> matrixB = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    vector<vector<int>> matrixC = {

        {9, 8, 7},

        {6, 5, 4},

        {3, 2, 1}

    };

    cout << “Matrix A:” << endl;

    printMatrix(matrixA);

    cout << “Matrix B:” << endl;

    printMatrix(matrixB);

    cout << “Matrix C:” << endl;

    printMatrix(matrixC);

    // Checking if matrixA and matrixB are equal

    if (areMatricesEqual(matrixA, matrixB)) {

        cout << “Matrix A and Matrix B are equal.” << endl;

    } else {

        cout << “Matrix A and Matrix B are not equal.” << endl;

    }

    // Checking if matrixA and matrixC are equal

    if (areMatricesEqual(matrixA, matrixC)) {

        cout << “Matrix A and Matrix C are equal.” << endl;

    } else {

        cout << “Matrix A and Matrix C are not equal.” << endl;

    }

    return 0;

}

Explanation

  1. Function areMatricesEqual:

  • Parameters:

Takes two 2D vectors (matrixA and matrixB).

  • Dimension Check:

First, checks if the dimensions of both matrices are the same.

  • Element-wise Comparison:

Iterates through each element, comparing corresponding elements in the matrices. If a mismatch is found, the function returns false.

  • Return Value:

If all corresponding elements are equal, the function returns true.

  1. Function printMatrix:

Prints the matrix in a formatted way for better visualization.

  1. Main Function:

  • Initializes three sample 3×3 matrices (matrixA, matrixB, and matrixC).
  • Prints the matrices.
  • Calls the areMatricesEqual function to check the equality of matrixA and matrixB, then matrixA and matrixC.
  • Outputs the results of the equality checks.

C++ Program to Add Two Matrices

Adding two matrices involves summing the corresponding elements of the matrices.

Problem Statement

Given two matrices of the same dimensions, add them element-wise and store the result in a new matrix.

Approach

  1. Matrix Validation: Ensure both matrices have the same dimensions.
  2. Element-wise Addition: Loop through each element of the matrices, add corresponding elements, and store the result in a new matrix.

Example

Given two 3×3 matrices:

Matrix A:

1 2 3

4 5 6

7 8 9

Matrix B:

9 8 7

6 5 4

3 2 1

The resulting matrix after addition:

10 10 10

10 10 10

10 10 10

C++ Code Implementation

#include <iostream>

#include <vector>

using namespace std;

// Function to add two matrices

vector<vector<int>> addMatrices(const vector<vector<int>>& matrixA, const vector<vector<int>>& matrixB) {

    int rows = matrixA.size();

    int cols = matrixA[0].size();

    vector<vector<int>> result(rows, vector<int>(cols, 0));

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

        for (int j = 0; j < cols; ++j) {

            result[i][j] = matrixA[i][j] + matrixB[i][j];

        }

    }

    return result;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing two 3×3 matrices

    vector<vector<int>> matrixA = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    vector<vector<int>> matrixB = {

        {9, 8, 7},

        {6, 5, 4},

        {3, 2, 1}

    };

    cout << “Matrix A:” << endl;

    printMatrix(matrixA);

    cout << “Matrix B:” << endl;

    printMatrix(matrixB);

    // Adding the two matrices

    vector<vector<int>> resultMatrix = addMatrices(matrixA, matrixB);

    cout << “Resultant Matrix after Addition:” << endl;

    printMatrix(resultMatrix);

    return 0;

}

Explanation

  1. Function addMatrices:
  • Parameters: Takes two 2D vectors (matrixA and matrixB).
  • Initialization: Initializes the result matrix with the same dimensions as the input matrices.
  • Element-wise Addition: Iterates through each element of the input matrices, sums the corresponding elements, and stores the result in the result matrix.
  1. Function printMatrix:

Prints the matrix in a formatted manner for better visualization.

  1. Main Function:

  • Initializes two sample 3×3 matrices (matrixA and matrixB).
  • Prints the original matrices.
  • Calls the addMatrices function to add the matrices.
  • Prints the resulting matrix after addition.

C++ Program to Find the Maximum and Minimum in an Array

Finding the maximum and minimum elements in an array is a common problem in programming.

Let’s start by outlining the steps to find the maximum and minimum elements in an array:

  1. Initialize two variables, max and min, to represent the maximum and minimum elements, respectively.
  2. Iterate through the array elements.
  3. For each element, compare it with the current maximum and minimum values.
  4. Update the maximum and minimum values if necessary.
  5. After iterating through all elements, max and min will hold the maximum and minimum elements of the array, respectively.

Here’s how we can implement this in C++:

#include <iostream>

#include <climits> // for INT_MAX and INT_MIN

using namespace std;

// Function to find the maximum and minimum elements in an array

void findMaxMin(int arr[], int size, int& max, int& min) {

    max = INT_MIN; // Initialize max to the smallest possible integer value

    min = INT_MAX; // Initialize min to the largest possible integer value

    // Iterate through the array elements

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

        // Update max if the current element is greater

        if (arr[i] > max) {

            max = arr[i];

        }

        // Update min if the current element is smaller

        if (arr[i] < min) {

            min = arr[i];

        }

    }

}

int main() {

    int arr[] = {3, 5, 2, 7, 9, 1, 4}; // Sample array

    int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

    int max, min; // Variables to store the maximum and minimum elements

    // Find the maximum and minimum elements in the array

    findMaxMin(arr, size, max, min);

    // Print the maximum and minimum elements

    cout << “Maximum element: ” << max << endl;

    cout << “Minimum element: ” << min << endl;

    return 0;

}

In this code:

  • We define a function findMaxMin that takes an array arr, its size size, and two references to integers max and min.
  • We initialize max to the smallest possible integer value using INT_MIN and min to the largest possible integer value using INT_MAX.
  • We iterate through each element of the array and update max and min accordingly.
  • In the main function, we initialize a sample array, call findMaxMin to find the maximum and minimum elements, and then print the results.
error: Content is protected !!