How to write the recursion code in calculating the sum of the array elements at odd value?

I understand the factorial example using recursion, but I am having a really big trouble when writing the recursion codes to perform anything else on my own :/ Please help with this task that I am stuck on.

I need to calculate the sum of the array elements at odd value using recursion.

I need to write the codes in:

public static double oddSum(double[] list, int sIndex, int eIndex) {
}

list is my double arrayList
sIndex is the initial index
eIndex is the end index

My idea is that my stopping point will be sIndex = eIndex, which would mean that I have checked every element on the list. I write the following code with confusion :/ I decided to paste it here to show that I am trying (even though the code is incorrect).

public static double oddSum(double[] numbers, int sIndex, int eIndex){
		int sum = 0;
		if(sIndex == eIndex)
			return sum;
		else
			if(sIndex+1%2 != 0)
				sum += numbers[sIndex+1];
		return sum;
	}

Please correct me if I have misunderstood. Thank you very much in advance.

Recommended Answers

All 2 Replies

One, if you are looking for odd numbers only, check whether sIndex is odd first thing. If not, make it odd by adding one to it.

Two, to avoid overflow, you should probably test whether sIndex >= eIndex rather than == eIndex.

Three, also to avoid overflow and other errors, it never hurts to check to make sure that numbers[] isn't null and that you are not trying to access an index >= its length. Similary, it never hurts to check for negative indexes. You can never have too many checks.

Fourth, I see no recursion here at all.

public static double oddSum(double[] numbers, int sIndex, int eIndex){
		int sum = 0;
		if(sIndex == eIndex)
			return sum;
		else
			if(sIndex+1%2 != 0)
				sum += numbers[sIndex+1];
		return sum;
	}

Recursion would be something like this...

public static double oddSum(double[] numbers, int sIndex, int eIndex){
		int sum = 0;
		if(sIndex == eIndex)
			return sum;
		else
			if(sIndex+1%2 != 0)
				sum += oddSum(numbers, sIndex+1, eIndex);
		return sum;
	}

That would be recursion, but you'd still have problems. Do a few by hand. Notice the pattern. Again, check whether sIndex is odd or even first thing.

VernonDozier,

Thank you very much for the helpful tips. The 4th comment you made really got me. I realized what I did wrong, and fixed my code.

Now my code checks whether it is an odd index by using sIndex%2 == 1. If it is, return the value, else return a 0. Then I have an else statement that recalls the method (thank you for the tip!) if it is an odd index, I add the previous sum to this new sum.

Thank you! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.