In what concerns the continuous evaluation solving exercises grade during the semester, you should submit until 23:59 of March 31st
(this exercise will still be available for submission after that deadline, but without couting towards your grade)
[to understand the context of this problem, you should read the class #04 exercise sheet]


In this problem you should submit a file containing the function as described (without any main function). Inside the function do not print anything that was not asked!

[PII030] Shifting Messages

Joyce is convinced that shifting numbers in an array can help her communicate with the Upside Down. She believes that by moving the numbers left or right, she can decode hidden messages from Will. Armed with her Christmas lights and sheer determination, she asks for your help to shift an array of integers k places in either direction.

Shifting an array means rotating it to the left or to the right. The shift should be circular, meaning elements pushed off one end should reappear on the other.

For example, imagine that the array is [1,2,3,4,5]. Shifting it one place to the right would result in [5,1,2,3,4], while shifting it one place to the left would result in [2,3,4,5,1]. Shifting it two places to the right would result in [4,5,1,2,3].

The Problem

Write a function void shift(int a[], int n, int k) that receives an array a[] of size n and an integer k. If k is positive, it should shift the array k positions to the right. If k is negative, it should shift it k positions to the left.

Constraints

The following limits are guaranteed in all the test cases that will be given to your program:

1 ≤ a[i] ≤ 100       Numbers in the array
1 ≤ n ≤ 100       Size of the array
-n < k < n       Number of places to shift

Submission

You should submit a .c file containing the requested function, without any main function and without printing anything. You can however create additional methods, if you need them.

Mooshak will use the following code to link to your function, read the inputs and call your method, printing its result.

#include <stdio.h>

// Forward declaration of function to implement
void shift(int [], int, int);

// print an array of size n (assume size >= 1)
void print_array(int a[], int n) {
  printf("[%d", a[0]);
  for (int i=1; i<n; i++)
    printf(",%d", a[i]);
  printf("]\n");
}

int main(void) {

  // Read array of n integers
  int n;
  scanf("%d", &n);
  int a[n];
  for (int i=0; i<n; i++)
    scanf("%d", &a[i]);

  // Read integer, shift the array and print before and after
  int k;
  scanf("%d", &k);
  print_array(a, n);
  shift(a, n, k);
  printf("After shift(a,%d,%d):\n", n, k);
  print_array(a, n);

  return 0;
}

Example Input 1 Example Output 1
6
1 2 3 4 5 6
1
[1,2,3,4,5,6]
After shift(a,6,1):
[6,1,2,3,4,5]

Example Input 2 Example Output 2
8
2 4 6 8 10 12 14 16
-3
[2,4,6,8,10,12,14,16]
After shift(a,8,-3):
[8,10,12,14,16,2,4,6]

Programming II (CCINF1002)
DCC/FCUP - University of Porto