+ 2
program
how it's work please tell me. http://www.sololearn.com/app/java/playground/cfQbq925cbrk/
2 ответов
+ 3
Well there's a method named find, that takes two arguments. It takes an integer argument and an array of integers.In the body of that method, it has a for loop that loops through the array that was passed in the parameters of the method to find the index of the integer that was passed in the method. Each time it loops i increments by 1, and it repeats through the length of the array. Until, it matches thus returning the index or where the integer is at in the array.
public class Program
{
static int find(int num,int[]n)
{
for (int i =0; i<n.length; i++)
if (n[i]==num )
return i;
return -1;
}
public static void main(String [] args) {
int []n={1,5,2,7,9,0};
System .out .println (find(0,n));
}
}
So in the main method we're initializing our array called n. Then we pass in 0 as the first argument and n(which is the array of integers in the second argument). The for loop will now iterate through the array to find where the integer 0 is located or the index of the of the element. So it returns 5, because the integer 0 is at the index of 5 in the array.
+ 1
so what is the use of return i nd return -1?