Exercise: Shift an Array Right
Let's do one more exercise before we move on to the next topic. This time I'll ask you to read an array, e.g. 1 2 3 4 5
, and shift it right once to get 5 1 2 3 4
, and print the shifted array.
For this exercise, and for many others, the input will be structured in a way that makes it easier to read. The first number in the input will be N
, the number of elements in an array. The following N
numbers will be array elements. So your code can expect an input similar to this:
5
1 2 3 4 5
and produce an output
5 1 2 3 4
To read an input like the one above, you can write the code like this:
int arr[1000];
int N, i;
scanf("%d", &N);
for (i = 0; i < N; ++i) {
scanf("%d", &arr[i]);
}
In the real life we would check the return value of each scanf
to make sure each of them returned 1 (read exactly one number), but we'll omit it in cases where the input is well defined.
The number N
will not be less than 1 or greater than 1000 in this exercise.
Ready to shift?
#include <stdio.h>
int main() {
/* your code here */
return 0;
}
Need a hint? When you shift an array once to the right, the last element (5 in the example) must be printed first. Other elements must be printed in their order. So whenever you read the number N
and then N
array elements as shown above, print the last one, which is arr[N - 1]
(because indexing starts from 0), and then print all elements from 0-th to N-1
-th in a for
loop.
Let me know if you have questions!