Go: Reverse a list

A slice keeps the numbers so you can use them in any order.

What to build

A program that prints a list of numbers backwards.

Requirements

  • Read n, then n whole numbers into a slice.
  • Print them in reverse order on one line, separated by single spaces.

Input

Line 1: n. Then n whole numbers.

Output

One line.

Constraints

1 ≤ n ≤ 100; each number is between -1000 and 1000.

Example

Input:

5
1 2 3 4 5

Output:

5 4 3 2 1

Why it works

You cannot print the last number first without remembering all the numbers; the slice does that. A loop from len(nums)-1 down to 0 visits them backwards.

Examples

Example 1 · Input
5
1 2 3 4 5
Expected output
5 4 3 2 1
Example 2 · Input
3
10 -20 30
Expected output
30 -20 10

Hints

Hint 1

Read the numbers into a slice with append.

Hint 2

Print the slice from the last index down to 0.

Solution

Show one correct solution (try it yourself first)
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	nums := []int{}
	for i := 0; i < n; i++ {
		var x int
		fmt.Scan(&x)
		nums = append(nums, x)
	}
	for i := len(nums) - 1; i >= 0; i-- {
		fmt.Print(nums[i])
		if i > 0 {
			fmt.Print(" ")
		}
	}
	fmt.Println()
}

▶ Open this solution in the compiler

Lesson: Arrays and slices →