ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
void rev(int *a, int l, int r) {
    while (l < r) {
        int t = a[l]; a[l] = a[r]; a[r] = t;
        l++; r--;
    }
}
int main(void) {
    int a[] = {1, 2, 3, 4, 5};
    rev(a, 0, 4);
    rev(a, 0, 1);
    rev(a, 2, 4);
    for (int i = 0; i < 5; i++) printf("%d ", a[i]);
}
  1. A. 5 4 3 2 1
  2. B. 4 5 1 2 3
  3. C. 3 4 5 1 2
  4. D. 4 5 3 2 1

Correct answer: B. 4 5 1 2 3

Reversing the whole array, then the first k elements, then the rest rotates the array right by k. Right-rotating {1,2,3,4,5} by 2 gives 4, 5, 1, 2, 3.

More C Programming questions

Exams that ask this topic