Challenge: Array Statistics
Completed
Read n, then n whole numbers. Print the sum, the smallest and the largest.
Input
First n (1 ≤ n ≤ 100), then n whole numbers.
Output
Sum: <sum> Min: <min> Max: <max>
Example
Input
5 3 8 -2 7 4
Output
Sum: 20 Min: -2 Max: 8
Editor
Java
Hints
Store the numbers in an int array of size n.
Start min and max at the first element, not at 0.
Solution explanation
Starting min and max at a[0] works even when every number is negative.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int sum = 0, min = a[0], max = a[0];
for (int x : a) {
sum += x;
if (x < min) min = x;
if (x > max) max = x;
}
System.out.println("Sum: " + sum);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module