Find Largest and Smallest Number in an Array

  1. /*

  2.   Find Largest and Smallest Number in an Array Example

  3.   This Java Example shows how to find largest and smallest number in an

  4.   array.

  5. */

  6. public class FindLargestSmallestNumber {

  7.  

  8. public static void main(String[] args) {

  9.  

  10. //array of 10 numbers

  11. int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};

  12.  

  13. //assign first element of an array to largest and smallest

  14. int smallest = numbers[0];

  15. int largetst = numbers[0];

  16.  

  17. for(int i=1; i< numbers.length; i++)

  18. {

  19. if(numbers[i] > largetst)

  20. largetst = numbers[i];

  21. else if (numbers[i] < smallest)

  22. smallest = numbers[i];

  23.  

  24. }

  25.  

  26. System.out.println("Largest Number is : " + largetst);

  27. System.out.println("Smallest Number is : " + smallest);

  28. }

  29. }

  30.  

  31. /*

  32. Output of this program would be

  33. Largest Number is : 98

  34. Smallest Number is : 23

  35. */

0 comments: