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 square matrix 90 degrees to the right in C++

1 Answer

0 votes
#include <iostream>

#define LEN 3 
   
void print_matrix(int matrix[][LEN]) { 
    for (int i = 0; i < LEN; i++) { 
        for (int j = 0; j < LEN; j++) 
            std::cout << " " << matrix[i][j]; 
        std::cout << std::endl;
    } 
    std::cout << std::endl;
} 
   
void rotate_matrix_90_degrees_right(int matrix[][LEN]) { 
    for (int i = 0; i < LEN / 2; i++) { 
        for (int j = i; j < LEN - i - 1; j++) { 
            int tmp = matrix[i][j]; 
            matrix[i][j] = matrix[LEN - 1 - j][i]; 
            matrix[LEN - 1 - j][i] = matrix[LEN - 1 - i][LEN - 1 - j]; 
            matrix[LEN - 1 - i][LEN - 1 - j] = matrix[j][LEN - 1 - i]; 
            matrix[j][LEN - 1 - i] = tmp; 
        } 
    } 
} 
     
int main() 
{ 
    int matrix[LEN][LEN] = 
    { 
        {1, 2, 3}, 
        {4, 5, 6}, 
        {7, 8, 9} 
    }; 
     
    rotate_matrix_90_degrees_right(matrix); 
   
    print_matrix(matrix); 
} 
   
   
   
/*
run:
   
 7 4 1
 8 5 2
 9 6 3
    
*/

 



answered May 19, 2019 by avibootz
edited May 29, 2025 by avibootz

Related questions

2 answers 137 views
1 answer 163 views
1 answer 166 views
1 answer 200 views
1 answer 144 views
1 answer 148 views
...