Find Smallest Number in an Array

Solution

  • Set the first element as smallest.
  • Loop through the array and check if current value < smallest, then set current value to smallest.
package com.java.programs;

public class SmallestNumber {

  public static int findSmallestNumber(int numbers[]) {
    int smallest = numbers[0];
    for(int number : numbers) {
      if(number < smallest) {
         smallest = number;
      }
    }
    return smallest;
   }

   public static void main(String[] args) {
     int[] numbers = {2,5,12,0,3,7,9,1};
     System.out.println(findSmallestNumber(numbers));
   }

}
0

Leave a Reply

Your email address will not be published. Required fields are marked *