The easiest way to do this is to regard the array as a linear sequence in memory:
int rotateDownN ( int x[][NumColumns], int nrows, int N ) { int j ; /* If N is out of range, return 0 */ if ( N < 0 || N > nrows*NumColumns) return 0; /* Save the first N entries */ int temp[N]; for ( j=0; j<N; j++ ) temp[j] = x[0][j]; /* Slide elements down */ for ( j=0; j<nrows*NumColumns-N; j++ ) x[0][j] = x[0][j+N]; /* Copy first N entries to last N positions */ for ( j=0; j<N; j++ ) x[0][nrows*NumColumns-N+j] = temp[j]; return 1; }
Remark: Many C compilers will not allow a local array variable with a size that depends the the value of a parameter:
int temp[N];
With such a compiler, the function must explicitly allocate and deallocate memory to hold the temporaries:
int rotateDownNmalloc ( int x[][NumColumns], int nrows, int N ) { int j ; int *temp; if ( N < 0 || N > nrows*NumColumns) return 0; temp = (int *)malloc( N*sizeof( int ) ); for ( j=0; j<N; j++ ) temp[j] = x[0][j]; for ( j=0; j<nrows*NumColumns-N; j++ ) x[0][j] = x[0][j+N]; for ( j=0; j<N; j++ ) x[0][nrows*NumColumns-N+j] = temp[j]; free ( temp ); return 1; }
It is possible to write this function without using any additional storage (other than a few index variables and one temporary.) But this method is complicated and offers no speed advantage.