C bootcamp · Lab 31

Reverse an array

mediumArrays12 minLesson: C Arrays

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n, then n integers. Print them in reverse order, space-separated.

You can print from the last index down, or swap in place then print forward.

Input. n, then n integers.

Output. The values in reverse order, space-separated.

Constraints

  • 1 ≤ n ≤ 100

Examples

Example 1
Input
5
1 2 3 4 5
Output
5 4 3 2 1
Hint
  1. Store in nums[100], then for (int i = n - 1; i >= 0; i--) print nums[i].
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  int n;
  int nums[100];
  if (scanf("%d", &n) != 1 || n < 1 || n > 100) return 1;
  for (int i = 0; i < n; i++) scanf("%d", &nums[i]);
  for (int i = n - 1; i >= 0; i--) printf("%d ", nums[i]);
  printf("\n");
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.