Swap the elements between any two given quadrants of a Matrix | C ++ program for the above approach ; Function to iterate over the X quadrant and swap its element with Y quadrant ; Iterate over X quadrant ; Swap operations ; Function to swap the elements of the two given quadrants ; For Swapping 1 st and 2 nd Quadrant ; For Swapping 1 st and 3 rd Quadrant ; For Swapping 1 st and 4 th Quadrant ; For Swapping 2 nd and 3 rd Quadrant ; For Swapping 2 nd and 4 th Quadrant ; For Swapping 3 rd and 4 th Quadrant ; Print the resultant matrix ; Function to print the matrix ; Iterate over the rows ; Iterate over the cols ; Driver Code ; Given matrix ; Given quadrants ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  6 NEW_LINE #define M  6 NEW_LINE void swap ( int mat [ N ] [ M ] , int startx_X , int starty_X , int startx_Y , int starty_Y ) { int row = 0 ; int col = 0 ; for ( int i = startx_X ; ; i ++ ) { col = 0 ; for ( int j = startx_X ; ; j ++ ) { int temp = mat [ i ] [ j ] ; mat [ i ] [ j ] = mat [ startx_Y + row ] [ starty_Y + col ] ; mat [ startx_Y + row ] [ starty_Y + col ] = temp ; col ++ ; if ( col >= M / 2 ) break ; } row ++ ; if ( row >= N / 2 ) break ; } } static void swapQuadOfMatrix ( int mat [ N ] [ M ] , int X , int Y ) { if ( X == 1 && Y == 2 ) { swap ( mat , 0 , 0 , 0 , M / 2 ) ; } else if ( X == 1 && Y == 3 ) { swap ( mat , 0 , 0 , N / 2 , 0 ) ; } else if ( X == 1 && Y == 4 ) { swap ( mat , 0 , 0 , N / 2 , M / 2 ) ; } else if ( X == 2 && Y == 3 ) { swap ( mat , 0 , M / 2 , N / 2 , 0 ) ; } else if ( X == 2 && Y == 4 ) { swap ( mat , 0 , M / 2 , N / 2 , M / 2 ) ; } else if ( X == 3 && Y == 4 ) { swap ( mat , N / 2 , 0 , N / 2 , M / 2 ) ; } printMat ( mat ) ; } void printMat ( int mat [ N ] [ M ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cout << mat [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { int mat [ ] [ M ] = { { 1 , 2 , 3 , 4 , 5 , 6 } , { 7 , 8 , 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 , 17 , 18 } , { 19 , 20 , 21 , 22 , 23 , 24 } , { 25 , 26 , 27 , 28 , 29 , 30 } , { 31 , 32 , 33 , 34 , 35 , 36 } } ; int X = 1 , Y = 4 ; swapQuadOfMatrix ( mat , X , Y ) ; }