Saturday, 10 October 2020

Java program to check that average of 5 numbers is greater than 150 or not

 Java program to check that average of 5 numbers is greater than 150 or not using if-else and java ternary operator. 


  1. public class Average {
  2.  
  3. /**
  4.   * Check that average of 5 number is greater than 150 or not
  5.   *
  6.   * @param args
  7.   */
  8. public static void main(String[] args) {
  9.  
  10. // using java if-else
  11. System.out.println("==== using java if-else ===");
  12. checkNumber(37, 45, 87, 100, 200); // Output -> Less than 150
  13. checkNumber(0, 500, 245, 784, 1); // Output -> Greater than 150
  14. checkNumber(27, 0, 8, 1, 88); // Output -> Less than 150
  15.  
  16. // using java ternary operator
  17. System.out.println("==== using java ternary operator ===");
  18. checkNumberUsingTernary(37, 45, 87, 100, 200); // Output -> Less than 150
  19. checkNumberUsingTernary(0, 500, 245, 784, 1); // Output -> Greater than 150
  20. checkNumberUsingTernary(27, 0, 8, 1, 88); // Output -> Less than 150
  21. }
  22.  
  23. // using java if-else
  24. private static void checkNumber(int n1, int n2, int n3, int n4, int n5) {
  25. int avg = (n1 + n2 + n3 + n4 + n5) / 5;
  26. if (avg > 150) {
  27. System.out.println("Greater than 150");
  28. } else {
  29. System.out.println("Less than 150");
  30. }
  31. }
  32.  
  33. // using java ternary operator
  34. private static void checkNumberUsingTernary(int n1, int n2, int n3, int n4, int n5) {
  35. int avg = (n1 + n2 + n3 + n4 + n5) / 5;
  36. String result = avg > 150 ? "Greater than 150" : "Less than 150";
  37. System.out.println(result);
  38. }
  39. }

Output
====  using java if-else ===
Less than 150
Greater than 150
Less than 150
====  using java ternary operator ===
Less than 150
Greater than 150
Less than 150

No comments:

Post a Comment