The following recursive method getNumberEqual searches the array x of n integers
ID: 3649900 • Letter: T
Question
The following recursive method getNumberEqual searches the array x of n integers for occurrences of the integer val. It returns the number of integers in x that are equal to val. For example, if x contains the 9 integers 1, 2, 4, 4, 5, 6, 7, 8, and 9, then getNumberEqual(x, 9, 4) returns the value 2 because 4 occurs twice in x.
public static int getNumberEqual(int x[], int n, int val) {
if (n <= 0) {
return 0;
}
else {
if (x[n-1] == val) {
return getNumberEqual(x, n-1, val) + 1;
}
else {
return getNumberEqual(x, n-1, val);
} // end if
} // end if
} // end getNumberEqual
Demonstrate that this method is recursive by listing the criteria of a recursive solution and stating how the method meets each criterion.
Explanation / Answer
Recursion is the process of repeating items in a self-similar way. in the provided example the sub-function getNumberEqual( ) is called by itself several times hence we cam say the given program is recursive. logic: if we found then we return getNumberEqual(x, n-1, val) + 1 else return getNumberEqual(x, n-1, val); this means that for every iteration we decrement the value of n and only add if the value matches
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.