Search code examples
javaarraysfor-loopmethodsnested-loops

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 it is 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, every time I just get the first number in the array. code:

    public static void main(String[] args) {
        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];
    }

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]