Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Summing every Xth element in an array. Write a method which takes an array of in

ID: 3686066 • Letter: S

Question

Summing every Xth element in an array. 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

Explanation / Answer

//I think the example is given wrong sumXArray({1,2,3,4,5,6}, 3, 0}) should return 1+4 = 5, sumXArray({1,2,3,4,5,6, 7, //8}, 3, 0}) should return 1+4+7 = 12

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
   public static void main (String[] args) throws java.lang.Exception
   {
       int data[] = {1,2,3,4,5,6};
       System.out.println(sumXArray(data, 3, 0));
      
   }
   public static int sumXArray( int data[], int skip, int current)
   {
       int size = data.length;
       if(current>=size)
           return 0;

       return data[current] + sumXArray(data, skip, current+skip);
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote