- There is no need to have a duplicate array of entire size. You can cycle the elements in one array itself. Try it on a piece of paper.
- You'll need to take backup of the 1st column every time, because that will be overwritten. Then, restore this backup.
I did it using simple array and some looping. Have a look at the code, it's self explanatory, and I've commented appropriately:
#include <stdio.h>
#include <stdlib.h>
#define M 2 //no of rows
#define N 5 //no of columns
int print(int (*matrix)[N]);
int main(void)
{
int matrix[M][N];
int backup[M];
int Z; //no of times to cycle
int i, j, k;
//get the i/p
printf("Enter matrix:\n");
for(i = 0 ; i < M ; i++)
for(j = 0 ; j < N ; j++)
scanf("%d", &matrix[i][j]);
//get Z
printf("How many times to cycle?\n");
scanf("%d", &Z);
//for Z = 0
if(Z == 0)
{
print(matrix);
return 0;
}
Z = (Z%N); //adjust Z to avoid unnecessary rotations because
//rotating an array of 5 columns 25 times is same as rotating 0 times
//(it will end up in original position after 25 rotations)
for(k = 0 ; k < Z ; k++) //first loop for Z rotations
{
//take backup of 1st col of matrix
for(int i = 0 ; i < M ; i++)
backup[i] = matrix[i][0];
for(i = N - 1 ; i >= 0 ; i--) //second loop for copying each column
{
//copy ith column into (i+1)%n th column
for(j = 0 ; j < M ; j++) //loop to copy all elements of column
{
matrix[j][(i+1)%N] = matrix[j][i]; //logic to wrap the last col to first one
}
}
//restore backup into 1st col
for(j = 0 ; j < M ; j++)
matrix[j][1] = backup[j];
}
print(matrix);
}
int print(int (*matrix)[N])
{
int i, j;
for(i = 0 ; i < M ; i++)
{
for(j = 0 ; j < N ; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
Here is a run of the sample program:
Enter matrix:
1 2 3 4 5
1 2 3 4 5
How many times to cycle?
1
5 1 2 3 4
5 1 2 3 4
aditya@aditya-laptop:~/Desktop$ cc so.c -std=c11&& ./a.out
Enter matrix:
1 2 3 4 5
1 2 3 4 5
How many times to cycle?
3
3 4 5 1 2
3 4 5 1 2
m
,n
? What are their values with respect tonumprocs
? What ismyid
? Voting to close because your are missing an MCVE stackoverflow.com/help/mcve++
and--
inside array designators. Your are changing your loop variables.