Just want to be clear, this is practice, not homework.

I'm attempting to understand this a bit better...but I'm a bit lost as what to use for my test...and what exactly will help me get to the base case.

Here is what I have so far

public class int SumOddN (int ar[], int n)
if ar.length == 0 || ar == null || ar.lenth <= n)
{
return 0;
}

if ar[n] % 2 == 0
{
return SumOddN(ar,n-1);
else return SumOddN(ar,n+1)+ar[n];
}


}


public static void main(String[] args)
{

int ar[]= {0,1,2,3,4,5};
System.out.println(SummOddN(ar,2));
System.out.println(SummOddN(ar,3));

}




}

Recommended Answers

All 4 Replies

First there are lots of typo's in your program. Remove them.

Your class cannot return an int. Your method should

public class void MyClass{

public static int myOddNoSumFunction(args){
 // functionality
}
public static void main(String[] args)
{
myOddNoSumFunction(myargs);
}

}

Note the usage of static. Try the same without static and check what happens.

It'l do you a lot of good to learn it this way. You may think of using a GUI tool. But be careful to track what is happening when you use one.

You don't an array for this program - the fact that it's there says that you are right to be learning more about recursion ;-)

Assuming that n is a positive odd integer, the recursive algorithm's pseudocode will look something simple like this:

method sumOdd(n)
  if n==1 return 1   (n<=1 would be that little bit safer)
  else return n + sumOdd(n-2)

I'll leave the Java up to you...

The array is what we are testing with...as the array is just the collection.

Testing what with? What collection?
Your title is "Adding Odd Numbers Using Recursive" - and there's nothing in your original post that reveals any need or relevance for an array. Maybe you can clarifywhat the array is doing here?

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.