Regarding the JAVA language assume that int[ ] a = {3, 5, 2, 4, 7, 3, 4, 5, 3} a
ID: 3698288 • Letter: R
Question
Regarding the JAVA language assume that int[ ] a = {3, 5, 2, 4, 7, 3, 4, 5, 3} and consider the two recursive methods below foo and bar. Consider these to answer the following questions.
1. What is the result of calling foo(a, 3, 0);?
2. What is the result of calling foo(a, 3, 4);?
3. What is the result of calling bar(a, 5);?
4. What is the result of calling bar(a, 9);?
public int foo(int[ ] a, int b, int j) {
if (j < a.length)
if (a[j] != b)
return foo (a, b, j+1);
else
return foo (a, b, j+1) + 1;
else
return 0;
}
public int bar(int[ ] a, int j) {
if (j < a.length)
return a[j] + bar(a, j+1);
else
return 0;
}
Explanation / Answer
1. What is the result of calling foo(a, 3, 0);?
Answer is 3,
Here foo(a,3,0) assume that a is an array and 3 is number check how many times its appear in the array, and from 0th position. In recusrsive function it is checking from 0th position to complete array.
it appers three times in an array.
2. What is the result of calling foo(a, 3, 4);?
in the same way here also checking for 3 but it checks from the fourth element of an array, here it appears two times so the result is : 2
3. What is the result of calling bar(a, 5);?
The result is : 15
In this one the numbers are adding from the 5th element of an array,
4. What is the result of calling bar(a, 9);?
Answer is : 0
because there are no elements after the given position.
Program:
class Test
{
public static void main(String ar[])
{
int [] a= {3, 5, 2, 4, 7, 3, 4, 5, 3};
System.out.println(foo(a,3,0));
System.out.println(foo(a,3,4));
System.out.println(bar(a,5));
System.out.println(bar(a,9));
}
public static int foo(int[ ] a, int b, int j)
{
if (j < a.length)
if (a[j] != b)
return foo (a, b, j+1);
else
return foo (a, b, j+1) + 1;
else
return 0;
}
public static int bar(int[ ] a, int j)
{
if (j < a.length)
return a[j] + bar(a, j+1);
else
return 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.