Advertisement
Guest User

Problem 5. Min, Max, Sum and Average of N Numbers

a guest
Mar 7th, 2021
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class MinMaxSumAndAverageOfNNumbers {
  6. public static void main(String[] args) {
  7. /*Write a program that reads from the console a sequence of
  8. n integer numbers and returns the minimal, the maximal number,
  9. the sum and the average of all numbers (displayed with 2 digits after the decimal point).
  10. The input starts by the number n (alone in a line)
  11. followed by n lines, each holding an integer number.
  12. The output is like in the examples below.
  13. */
  14. Scanner sc = new Scanner(System.in);
  15. int n = Integer.parseInt(sc.nextLine());
  16. int[] inputs = new int[n];
  17. for (int i = 0; i < n; i++) {
  18. inputs[i] = Integer.parseInt(sc.nextLine());
  19. }
  20. // for (int i = 0; i < n; i++) {
  21. // if (i == n - 1) continue;
  22. int max = inputs[0];
  23. int min = inputs[0];
  24. int sum = inputs[0];
  25. double avg = Double.parseDouble(String.valueOf(inputs[0])); // /n
  26.  
  27. for (int i = 0; i < n; i++) {
  28. min = Math.min(min, inputs[i]);
  29. max = Math.max(max, inputs[i]);
  30. sum = Integer.sum(sum, inputs[i]);
  31. avg = (Double.sum(sum, inputs[i])) / n;
  32. }
  33.  
  34.  
  35. System.out.println("min = " + min);
  36. System.out.println("max = " + max);
  37. System.out.println("sum = " + sum);
  38. System.out.printf("avg = %.2f", avg);
  39.  
  40. }
  41. }
  42.  
  43. /* Examples:
  44. n output
  45. 3
  46. 2
  47. 5
  48. 1 min = 1
  49. max = 5
  50. sum = 8
  51. avg = 2.66
  52.  
  53.  
  54. n output
  55. 2
  56. -1
  57. 4 min = -1
  58. max = 4
  59. sum = 3
  60. avg = 1.5
  61. */
  62.  
  63.  
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement