136k views
5 votes
Write a method smallestPositive that takes an integer array argument and returns the smallest positive element in the array.

1 Answer

4 votes

Answer:

public class Main

{

public static void main(String[] args) {

int[] arr = {28, 7, -51, -2, 221};

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

}

public static int smallestPositive(int[] arr){

int heighest = arr[0];

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

if(arr[i] > heighest)

heighest = arr[i];

}

int lowest = heighest;

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

if(arr[i] < lowest && arr[i] > 0)

lowest = arr[i];

}

return lowest;

}

}

Step-by-step explanation:

The code is in Java.

Create a method named smallestPositive that takes one parameter, arr

Inside the method:

Find the largest value in the array using the first for loop

Set the this value as lowest to find the smallest positive value (I assumed there is at least on positive value in the array)

Create another for loop to iterate through the array. If a value is smaller than the lowest and if it is greater than 0, set it as lowest

When the loop is done, return the lowest

Inside the main method:

Initialize an array with some numbers

Call the smallestPositive() with this array and print the result

(In our example, the result would be 7)

User Atrag
by
5.3k points