Row-wise Shift of Matrix Elements using C++
Our task is to shift the elements of the matrix row-wise in C++ programming. That means, we shift the elements of the matrix row by row by a certain value and display the result.
We have the square matrix of size N*N, whose elements are to be shifted row-wise. And we have a shift_value, by which we shift the elements of the matrix, in each row.
A key point which has to be remembered here is: The matrix should be a square matrix always.
For example:
- Input : matrix[N][N] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
shift_value = 2
Output : 3 1 2
6 4 5
9 7 8
- Input : matrix[N][N] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
shift_value = 2
Output : 3 4 1 2
7 8 5 6
11 12 9 10
15 16 13 14
C++ code for Row-wise Shifting of elements in a matrix
#include <bits/stdc++.h>
using namespace std;
#define N 4
//function to row wise shift elements of each row of the matrix
void shift_matrix_elements(int matrix[N][N], int shift_value)
{
//variables used
int i, j=0;
//condition to check if shift value is greater then size
if(shift_value>N)
{
cout<<"\nRow wise element shift is not possible.";
cout<<"\nTry again with a lower number."<<endl;
return;
}
//row wise shifting of elements
cout<<"\nThe new row wise shifted matrix is: "<<endl;
while(j<N)
{
//printing matrix elements from shift_value index
for(i=shift_value ; i<N ; i++)
cout<<matrix[j][i]<<" ";
//printing elements before shift_value index
for(i=0 ; i<shift_value ; i++)
cout<<matrix[j][i]<<" ";
cout<<endl;
j++;
}
}
//int main/driver code
int main()
{
//variables used
int i,j;
//stores value by which row wise matrix elements are shifted
int shift_value;
//creating a 4*4 matrix to rotate
int matrix[N][N]= { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
//print the original matrix
cout<<"The matrix before the row-wise shift is:"<<endl;
for(i=0 ; i<N ; i++)
{
for(j=0 ; j<N ; j++)
cout<<matrix[i][j]<<" ";
cout<<endl;
}
//taking the row wise shift value from the user
cout<<"\nEnter the value the row-wise shift the matrix by: ";
cin>>shift_value;
//calling the function to row wise shift the matrix elements
shift_matrix_elements(matrix, shift_value);
return 0;
}
Output for Row-wise Shift
- CASE 1 – when shift_value is greater than the size of the array
The matrix before the row-wise shift is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Enter the value the row-wise shift the matrix by: 7 Row wise element shift is not possible. Try again with a lower number.
- CASE 2 – when shift_value is less than or equal to the size of the array
The matrix before the row-wise shift is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Enter the value the row-wise shift the matrix by: 2 The new row wise shifted matrix is: 3 4 1 2 7 8 5 6 11 12 9 10 15 16 13 14
NOTE
- The array has to be square.
- The shift by a value equal to the size of the array results in the original array itself.
Hope this helps!
You could check out the following too!
Leave a Reply