ProgrammingHardTCS NQT · Infosys

What is printed?

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

Correct answer: A. 2 1 4 3 5

The loop swaps the pairs (0,1) and (2,3) and stops before index 4 because i + 1 is not less than 5 there, so the last element stays put.

More C Programming questions

Exams that ask this topic