Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I run my for-loop, the returned value is not the correct array value

I have tried to switch values, numbers, variables, everything, and nothing seems to work. I am still quite new to arrays so I apologize if its a simple fix.

The nested loop is supposed to find the smallest value in the array and then return it to the main method, however, everytime I just get the first number in the array.
code:

````        {
````        int[] arr = {2, 1, 4, 3, 6, 5, 8, 7};
````        int min;
````        min = findMin(arr);
````        System.out.println("Smallest value: " + min);
````        }

````public static int findMin(int[] arr)
````    {
````        int min = arr[0];
````        for(int i = 0; i < arr.length; i++)
````        {
````            if(arr[i] < min);
````            {
````                min = arr[i];
````            }
````        }
````        return arr[min];
````    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are two issues in your code,

  1. remove the semicolon from the line where there’s an if condition, with the semicolon at the end of the line if condition line is considered as a single statement

            if (arr[i] < min) 
            {
                min = arr[i];
            }
    
  2. Also, return the min instead of arr[min]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading