Using only java recursion not loops or a scanner. Write a method which takes an
ID: 3686727 • Letter: U
Question
Using only java recursion not loops or a scanner. Write a method which takes an array of integers, and an integer indicating which elements to sum (1 means sum every element, 2 means sum every other element, 3 means sum every 3rd element etc.) A third parameter (an integer) will be needed to implement this functionality recursively. (Hint: think about how an index is used). The method should return the sum of every Xth element in the array (based on the last parameter), starting from index 0. You may assume that the starting index will be valid for the given array.
Examples:
sumXArray({1,2,3,4,5,6}, 1, 0}) returns 21
sumXArray({1,2,3,4,5,6}, 3, 0}) returns 9
sumXArray({1,2,3,4,5,6, 7, 8}, 3, 0}) returns 9
the Xth element should go by ordinal numbers not by the index number so the examples given are correct
Explanation / Answer
/**
* @author Srinivas Palli
*
*/
public class SumXthElement {
/**
* @param args
*/
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
int[] b = { 1, 2, 3, 4, 5, 6, 7, 8 };
// calling recursive function
System.out.println("sumXArray({ 1, 2, 3, 4, 5, 6 }, 1, 0)-->"
+ sumXArray(a, 1, 0));
System.out.println("sumXArray({ 1, 2, 3, 4, 5, 6 }, 3, 0)-->"
+ sumXArray(a, 3, 0));
System.out.println("sumXArray({ 1, 2, 3, 4, 5, 6,7,8 }, 3, 0)-->"
+ sumXArray(b, 3, 0));
}
/**
*
* recursive method to find the sum of xth elements
*
* @param array
* @param x
* @param i
* @return
*/
public static int sumXArray(int array[], int x, int i) {
if (i >= array.length)
return 0;
else if ((i + 1) % x == 0) {
return array[i] + sumXArray(array, x, i + 1);
} else
return 0 + sumXArray(array, x, i + 1);
}
}
OUTPUT:
sumXArray({ 1, 2, 3, 4, 5, 6 }, 1, 0)-->21
sumXArray({ 1, 2, 3, 4, 5, 6 }, 3, 0)-->9
sumXArray({ 1, 2, 3, 4, 5, 6,7,8 }, 3, 0)-->9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.