Question: I am trying to get the second smallest number using two for loops. I seem to be getting the third smallest. can anyone help ?

I am trying to get the second smallest number using two for loops. I seem to be getting the third smallest. can anyone help ?

public static void main (String args[]) {

int [] arr = {2,7,1,9,3};

System.out.println(minNum1(arr));

System.out.println(minNum2(arr));

}

public static int minNum1(int [] arr ) {

int min = 0;

int secondMin = 0;

for(int i = 0; i < arr.length; i++) {

for(int j = i + 1; j < arr.length; j++) {

if(arr[i] < arr[j]) {

secondMin = arr[j];

min = arr[i];

}

}

}

return secondMin;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!