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

Time:11-30

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];
````    }

CodePudding user response:

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]

CodePudding user response:

You should replace this line if(arr[i] < min); with if(arr[i] < min)

and return arr[min]; with return min;

CodePudding user response:

I believe it should return the "min" variable; otherwise, you are asking it to find and return the "min" index in the array. If the smallest value in the array was, let's say, 100, the code would have a compile error because the array does not have 100 values in it.

````        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 min;
````    }

CodePudding user response:

First of all you should declare the length of the array using the length method at some point so you can reference it in your for loop:

int len = arr.length();

Second of all, the code should return the minimum, not the array at the index equal to the minimum number.

return min;
  • Related