Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: hey guys new to recursion any ideas for me?

1. ## hey guys new to recursion any ideas for me?

Im supposed to Write a recursive method that computes the sum of the first n strictly positive integers. Im new to recursion any help would be great. im getting errors at moment...

[/
HTML Code:
```mport java.util.Scanner;
public class SumTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);

int sum = 0;
System.out.println("\nPlease Enter n"); // get n from user
int n = in.nextInt();

}

}
// recursively computes the sum of the first n integers
public static int sum(int n)
{
int sum = n;
if (N == 1) return 1;
return N * sum(N-1);
System.out.println("Recursively computing sum of the first 5 positive integers");
System.out.println("Sum" + n + "=" + sum);
//return sum;
}

}```

2. ## Re: hey guys new to recursion any ideas for me?

Your algorithm needs a little work. Try this:

1. See if your current number n is 1. If it is, return 1.
2. Otherwise, sum(n) = sum(n-1) + n

3. ## Re: hey guys new to recursion any ideas for me?

many thanks for the reply helloworld i have ammended it but having one error cant quiet see where im going wrong.
HTML Code:
```import java.util.Scanner;
public class SumTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("\nPlease Enter n"); // get n from user
int n = in.nextInt();
}

// recursively computes the sum of the first n integers
public static int sum(int n)
{
if (n ==1)
return 1;
else
return sum(n) = sum(n-1) + n;

System.out.println("sum" + (n) + "=" + (n));
}

}```

4. ## Re: hey guys new to recursion any ideas for me?

Welcome back, Steve's got you stumped on the first question I see.

use [code][/code] tags rather than html tags.

Also you might wish to actually call your recursive method.

5. ## Re: hey guys new to recursion any ideas for me?

Your printing out statement in sum can never be reached (can you see why?). Java's compiler recognizes this and will through an error. Put that print out statement somewhere inside your main method, and as chris said, call the method

`System.out.println("The sum is " + sum(n));`