i've been asked create public method nothing call method recursive. purpose of second method search int value inside array.
so far have this:
int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100}; int cont = 0; public int searchi(int x) { searchr(x); return x; } private void searchr(int y) { if (cont < array.length) { if (array[cont] == y) { system.out.println(y); } else { searchr(cont++); } } } however, no matter number use, either 1 in array or not, prints value of y. i'm still new recursion , not quite grasping essence of yet. that's why method isn't working (besides wrong). thoughts? , probably, grasp term better.
as far code, print y when finds y in array because of
if (array[cont] == y) { system.out.println(y); } and after first call of searchr(x) searching value of cont instead of value of x. change searchr(cont++)
cont++; searchr(y); if want position of number you're searching use system.out.println(cont) instead of system.out.println(y).
int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100}; int cont = 0; public int searchi(int x) { searchr(x); return x; } private void searchr(int y) { if (cont < array.length) { if (array[cont] == y) { system.out.println(y); //system.out.println(cont); if want position output } else { cont++; searchr(y); } } }
Comments
Post a Comment