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,851 questions

51,772 answers

573 users

How to reverse N x N matrix in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
  
#define ROWS 3
#define COLS 3
  
void print_matrix(int matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            printf("%4i", matrix[i][j]);
           
        printf("\n");
    }
}
 
void reverse_matrix(int matrix[][COLS], int rows, int cols) {
    int i, j, counter = 0;
      
    for (int r = rows - 1, i = 0; i < rows; i++, r--) {
        for (int c = cols - 1, j = 0; j < cols; j++, c--) {
            int tmp = matrix[i][j];
            matrix[i][j] = matrix[r][c];
            matrix[r][c] = tmp;
            counter++;
            if (counter > (rows * cols) / 2 - 1) return; // stop from the middle of the matrix
        }
    }
}
 
int main(void)
{
    int i, j, matrix[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
     
    printf("matrix 1:\n");
    print_matrix(matrix, ROWS, COLS);
    reverse_matrix(matrix, ROWS, COLS);
    printf("reverse matrix 1:\n");
    print_matrix(matrix, ROWS, COLS);
      
    srand(time(NULL));
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            matrix[i][j] = rand() % 10 + 1;
        }
    }
      
    printf("\n\nmatrix 2:\n");
    print_matrix(matrix, ROWS, COLS);
    reverse_matrix(matrix, ROWS, COLS);
    printf("reverse matrix 2:\n");
    print_matrix(matrix, ROWS, COLS);
      
    return 0;
}


/*
run:

matrix 1:
   1   2   3
   4   5   6
   7   8   9
reverse matrix 1:
   9   8   7
   6   5   4
   3   2   1


matrix 2:
   2   2  10
   2   7   4
   1   3  10
reverse matrix 2:
  10   3   1
   4   7   2
  10   2   2
  
*/


answered Sep 23, 2014 by avibootz
edited Apr 20, 2025 by avibootz
...