# Help needed with a Java exercise

• 05-14-2011, 12:08 PM
maniku
Help needed with a Java exercise
Hi all,

I'm taking a java programming course, and can't figure out an exercise. Could someone help?

The exercise is to create a programme which asks the user to give a value for n and then calculate the sum of:

1 + 2 + 3 + ... + n

(e.g. if n = 6, it would be 1 + 2 + 3 + 4 + 5 + 6)

But: you have to do it WITHOUT using a loop.

I can't get further than:

Code:

```import java.util.*; public class T27_Summa1_2_3_n {     private static Scanner input = new Scanner(System.in);     public static void main(String[] args) {         System.out.print("Anna n: ");         int n = Integer.parseInt(input.nextLine());     } }```
Probably some obvious solution which I'm totally missing... Thanks!
• 05-14-2011, 12:27 PM
sunde887
Try using a recursive method.

I'll quickly explain what recrsion is but I don't want to ruin it for you so I'll save examples for if you get really stuck.
A recursive method generally is broken down into it's parts, one part is a termination clause, what should occur for the method to finally return? The other part is a recursive call. To keep it simple let's work with a recursive process. The method should do something then call itself.

Here is a good recursive definition, I'll leave the translation and base case to you

To find the sum of numbers up to n you want to:
Add n to sum(n - 1)

Code:

```public int sumN(int n){   if condition is met     return base case   else     do something and make a recursive call }```
A recursive call is a method calling itself. Recursion is a bit strange coming from usig loops so it may take a bit to sink on, however; it's definitely nice to understand.
• 05-14-2011, 02:04 PM
maniku
Solved:

Code:

```import java.util.*; public class T27_Summa1_2_3_n {     private static Scanner input = new Scanner(System.in);     public static int summa(int n) {     if (n == 1) {         return 1;     } else {         return n + summa(n - 1);     } }         public static void main(String[] args) {         System.out.print("Anna n: ");         int n = Integer.parseInt(input.nextLine());         System.out.println("Tulos: " + summa(n));     } }```
Thank you for your pointers, sunde887!
• 05-14-2011, 02:09 PM
sunde887