Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to rotate a matrix 90 degrees clockwise in C++

2 Answers

0 votes
#include <iostream>

const int N = 3; // Matrix size

void rotate90Clockwise(int matrix[N][N]) {
    // Step 1: Transpose the matrix
    for (int i = 0; i < N; i++) {
        for (int j = i; j < N; j++) {
            std::swap(matrix[i][j], matrix[j][i]);
        }
    }

    // Step 2: Reverse each row
    for (int i = 0; i < N; i++) {
        for (int j = 0, k = N - 1; j < k; j++, k--) {
            std::swap(matrix[i][j], matrix[i][k]);
        }
    }
}

// Function to print the matrix
void printMatrix(int matrix[N][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    int matrix[N][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    std::cout << "Original Matrix:\n";
    printMatrix(matrix);

    rotate90Clockwise(matrix);

    std::cout << "\nRotated Matrix:\n";
    printMatrix(matrix);
}

  
  
/*
run:
  
Original Matrix:
1 2 3 
4 5 6 
7 8 9 

Rotated Matrix:
7 4 1 
8 5 2 
9 6 3 

  
*/

 



answered May 29, 2025 by avibootz
0 votes
#include <iostream>

const int ROWS = 3; // Original matrix rows
const int COLS = 4; // Original matrix columns

void rotate90Clockwise(int matrix[ROWS][COLS], int rotated[COLS][ROWS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            rotated[j][ROWS - 1 - i] = matrix[i][j]; // Mapping to rotated position
        }
    }
}

// Function to print a matrix
void printMatrix(int rows, int cols, int matrix[][3]) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    int matrix[ROWS][COLS] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };

    int rotated[COLS][ROWS]; // New rotated matrix

    rotate90Clockwise(matrix, rotated);

    std::cout << "Rotated Matrix:\n";
    printMatrix(COLS, ROWS, rotated);
}

   
   
/*
run:
   
Rotated Matrix:
9 5 1 
10 6 2 
11 7 3 
12 8 4 
    
*/

 



answered May 29, 2025 by avibootz

Related questions

1 answer 149 views
2 answers 131 views
2 answers 138 views
2 answers 149 views
2 answers 173 views
2 answers 137 views
2 answers 129 views
...