java

Java Program to find the smallest number in an Array

In this post, we are going to see how to find the smallest number in an Array using core Java program.

So, here is the complete program for you (JavaSmallestInArray.java):

The output of the above program is: 

Please go through inline comments in the above program to understand it. But the basic idea is, we are swapping the array values each time when there is the smallest number.

Here is a detailed explanation of the above program about the swapping,

//this is our array and the array length is 7
int arr[] = {10, 20, 101, 122, 1, 5, 12};

Let’s see the loop and if condition:

  1. if (a[0] < a[1]) ie., if (10 < 20) – is true, so need to swap the value
    • let’s swap, a[0] = 20, a[1] = 10
  2. if (a[1] < a[2]) ie., if (10 < 101) – is true again, so, swap the value again
    • let’s swap, a[1] = 101, a[2] = 10
  3. if (a[2] < a[3]) ie., if (10 < 122) – is true again, so, swap the value again
    • let’s swap, a[2] = 122, a[3] = 10
  4. if (a[3] < a[4]) ie., if (10 < 1) – is false, so nothing happens here
  5. if (a[4] < a[5]) ie., if (1 < 5) – is true again, so, swap the value again
    • let’s swap, a[4] = 5, a[5] = 1
  6. if (a[5] < a[6]) ie., if (1 < 12) – is true again, so, swap the value again
    • let’s swap, a[5] = 12, a[6] = 1

So, the smallest number is at the end of the array arr[6] = 1. That’s the value we are printing at the end.

Related Posts

Leave a Reply