Why doesn't my program handle shifts greater than the length of the array

My program is supposed to right shift an integer array of N length in ascending order (For example: {1,2,3,4} or {21,22,23}) by M elements. My program works fine except for if the number of shifts is greater than the length of the array. For example if the array is 52 integers it will right shift fine up to 51 elements, but once it goes past 52 it no longer works. Why not and what is wrong? Also, please don't point out that the M loop is "unnecessary" because the M loop is required for the project.
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 #include <iostream>
#include <string>
#include <vector>
using namespace std;

/**
 * PURPOSE: Takes in an integer array (arr[]), its length (N), and the number of elements to right-shift (M):
 * PARAMETERS:
 *     arr[] , integer array
 *     N , its length
 *     M , number of elements to right shift
 * RETURN VALUES:
 *     the new array after right shifting the elements.
*/
 

void rightShiftElementsbyOne(int arr[], int N);
 
/*Function to right rotate arr[] of size N by M elements*/
void rightShiftElements(int arr[], int N, int M)
{
  int i;
  for (i = 0; i < N - M; i++)
    rightShiftElementsbyOne(arr, N);
   
}
 
void rightShiftElementsbyOne(int arr[], int N)
{
  int i, temp;
  temp = arr[0];
  for (i = 0; i < N-1; i++)
     arr[i] = arr[i+1];
  arr[i] = temp;
}
 
/* utility function to print an array */
void printArray(int arr[], int size)
{
  int i;
  for(i = 0; i < size; i++)
    printf("%d ", arr[i]);
}
 
/* Driver program to test above functions */
int main()
{
    
    // it shifts to the right if (N - 2)+ M
   int arr[] = {1, 2, 3, 4, 5, 6, 7};
   rightShiftElements(arr, 7, 9);
   printArray(arr, 7);
   getchar();
   return 0;
}


As you can see it doesn't work for right shifting an array of 7 length 9 times. But it works for right shifting the array any number of times between 1-6.
Last edited on
Topic archived. No new replies allowed.