how to find smallest number in array java

www.lau‮t‬turi.com
how to find smallest number in array java

To find the smallest number in an array in Java, you can use a loop to iterate over the array and compare each element to a variable holding the current smallest number.

Here's an example of how to find the smallest number in an array in Java:

int[] numbers = {5, 3, 8, 1, 9, 4};

int smallest = numbers[0];

for (int i = 1; i < numbers.length; i++) {
  if (numbers[i] < smallest) {
    smallest = numbers[i];
  }
}

System.out.println("The smallest number is " + smallest);

In the above example, an array of integers is defined and initialized with six elements. A variable called smallest is initialized with the value of the first element in the array.

A loop is then used to iterate over the array starting from the second element. For each element in the array, the if statement checks if the element is smaller than the current value of smallest. If it is, the value of smallest is updated to the value of the element.

After the loop completes, the value of smallest is printed to the console.

Keep in mind that this example assumes that the array is not empty. If the array is empty, the code will throw an ArrayIndexOutOfBoundsException when it tries to access the first element. You should check the length of the array before iterating over it to avoid this exception.

For example:

int[] numbers = {};

if (numbers.length == 0) {
  System.out.println("The array is empty");
} else {
  int smallest = numbers[0];

  for (int i = 1; i < numbers.length; i++) {
    if (numbers[i] < smallest) {
      smallest = numbers[i];
    }
  }

  System.out.println("The smallest number is " + smallest);
}

In this example, the length of the array is checked before the loop is executed. If the array is empty, a message is printed to the console stating that the array is empty. If the array is not empty, the loop is executed and the smallest number is found as before.

Created Time:2017-11-01 20:42:52  Author:lautturi