Store numbers in an array so you can visit them again in another order.
What to build
A program that prints numbers in reverse order and their sum.
Requirements
- Read n, then n whole numbers into an
int[]. - Print the numbers in reverse order, separated by spaces, then
sum: S.
Input
Line 1: n. Line 2: n whole numbers.
Output
Two lines.
Constraints
1 ≤ n ≤ 1000; |each number| ≤ 10^6.
Example
Input:
5
1 2 3 4 5
Output:
5 4 3 2 1
sum: 15
Why it works
An array keeps every number, so after reading them all the program can walk back from the last index to the first.
Examples
Example 1 · Input
5 1 2 3 4 5
Expected output
5 4 3 2 1 sum: 15
Example 2 · Input
1 -7
Expected output
-7 sum: -7
Hints
Hint 1
Fill an int array of size n, then loop from n - 1 down to 0.
Hint 2
Add the numbers up in the same loop that reads them.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum += a[i];
}
StringBuilder sb = new StringBuilder();
for (int i = n - 1; i >= 0; i--) {
sb.append(a[i]);
if (i > 0) sb.append(' ');
}
System.out.println(sb);
System.out.println("sum: " + sum);
}
}