program | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
24th Oct 2016, 3:34 AM
Sadab Khan
Sadab Khan - avatar
2 Answers
+ 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.
24th Oct 2016, 3:47 AM
Don
Don - avatar
+ 1
so what is the use of return i nd return -1?
24th Oct 2016, 3:56 AM
Sadab Khan
Sadab Khan - avatar