C++ Program to Rotate Matrix Elements of a Matrix

Rotating Matrix elements in a C++ program involves rearranging the elements of a matrix by rotating them either clockwise or counterclockwise. Here’s a brief explanation of how to achieve this within a 400-word limit:

To begin, let’s consider rotating a square matrix. We’ll create a C++ function to rotate the matrix elements clockwise by 90 degrees. The steps involved are:

  1. Transpose the matrix.
  2. Reverse each row of the transposed matrix.

Here’s the implementation:

#include <iostream>

#include <vector>

using namespace std;

// Function to rotate the matrix elements clockwise by 90 degrees

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

    int N = matrix.size(); // Size of the matrix

    // Transpose the matrix

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

        for (int j = i; j < N; ++j) {

            swap(matrix[i][j], matrix[j][i]);

        }

    }

    // Reverse each row

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

        for (int j = 0; j < N / 2; ++j) {

            swap(matrix[i][j], matrix[i][N – 1 – j]);

        }

    }

}

// Function to print the matrix

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

    for (const auto& row : matrix) {

        for (int num : row) {

            cout << num << ” “;

        }

        cout << endl;

    }

}

int main() {

    vector<vector<int>> matrix = {{1, 2, 3},

                                   {4, 5, 6},

                                   {7, 8, 9}};

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

    printMatrix(matrix);

    rotateMatrix(matrix);

    cout << “Matrix After Rotation:” << endl;

    printMatrix(matrix);

    return 0;

}

In this code:

  • We define a function rotateMatrix that takes a 2D vector matrix as input.
  • We find the size N of the matrix.
  • We iterate through each element of the matrix to transpose it.
  • Then, we reverse each row of the transposed matrix.
  • We define a printMatrix function to print the matrix.
  • In the main function, we initialize a sample matrix, print it, rotate it, and then print the rotated matrix.

This code demonstrates rotating a square matrix clockwise by 90 degrees. Similar techniques can be applied for rotating non-square matrices or rotating counterclockwise by modifying the logic accordingly.

Leave a Reply

error: Content is protected !!