Smallest and largest number in an array in JAVA programming


  1.  
  2. //Alamgir Hossain, CSE, JUST
  3.  
  4. import java.util.Scanner;
  5.  
  6.  
  7. public class LargestandSmallest {
  8.  
  9.  
  10. public static void main(String[] args) {
  11.  
  12. Scanner myScanner=new Scanner(System.in);
  13.  
  14.  
  15.  
  16. int n;
  17.  
  18. int[] arr=new int[100];
  19.  
  20. System.out.print("Enter the number of elements : ");
  21.  
  22. n=myScanner.nextInt();
  23.  
  24. System.out.print("Enter "+n+" numbers : ");
  25.  
  26. for (int i = 0; i < n; i++) {
  27.  
  28. arr[i]=myScanner.nextInt();
  29.  
  30. }
  31.  
  32. int small,large;
  33.  
  34. small=arr[0];
  35.  
  36. large=arr[0];
  37.  
  38. for (int i = 0; i < n; i++) {
  39.  
  40. if (small>arr[i]) {
  41.  
  42. small=arr[i];
  43.  
  44. }
  45.  
  46. else if(large<arr[i]){
  47.  
  48. large=arr[i];
  49.  
  50. }
  51.  
  52. }
  53.  
  54. System.out.print("Smallest number is : "+small);
  55.  
  56. System.out.println();
  57.  
  58. System.out.print("Largest number is : "+large);
  59.  
  60. }
  61.  
  62.  
  63. }
  64.  

No comments:

Post a Comment