th30d0rab1e
th30d0rab1e

Reputation: 119

Sum of Numbers Recursion

I want to display every number leading up to the variable 'number'.

Example, if the number is 5, I would want the result to be 1 2 3 4 5. I have an error for returning a value, I'm not sure why. How do I return the results using recursion?

public class SumOfNumbers {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Number?");
    int number = keyboard.nextInt();
    System.out.println(recursion(number));
}
public static int recursion(int number)
{
    for (int i=0;i>number;i++)
    {
        return recursion(i);
    }
    else {
        return number ;
        }
    }

}

Upvotes: 0

Views: 130

Answers (3)

Makandal
Makandal

Reputation: 151

This short code will also print the numbers right.

public void recursion(int number){
    if (number>1)
        recursion(number-1);
    System.out.println(number);
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You are mixing recursion and iteration. The for loop is unnecessary in your recursive solution.

Think of your recursive solution as if it already exists: what would you do if a program "print numbers up to n-1" was given to you, and you were asked to write a program that prints numbers up to n? The solution would be pretty clear - you would write it like this:

void myRecursiveProgram(int n) {
    if (n == 0) {
        return; // do nothing
    }
    printNumbersUpToN(n-1); // Go up to n-1 using the "magic solution"
    System.out.println(n);  // Complete the task by printing the last number
}

Now observe that myRecursiveProgram is your printNumbersUpToN program, so all you need to do is renaming it:

void printNumbersUpToN(int n) {
    if (n == 0) {
        return; // do nothing
    }
    printNumbersUpToN(n-1);
    System.out.println(n);
}

Note the if (n == 0) step: it's very important, because it prevents your recursion from going non-stop into negative territory. This is called the base case of recursion - i.e. the case when you do a fixed amount of work, or no work at all.

Upvotes: 3

Your code doesn't compile, you have an else without if.

What you are trying to do is something like:

import java.util.Scanner;
public class SumOfNumbers {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Number?");
    int number = keyboard.nextInt();
    recursion(number);
}
public static void recursion(int number)
{
    if (number>1)
    {
        recursion(number-1);
        System.out.print(number);
    }
    else {
        System.out.print(number);
    }

}

}

Upvotes: 2

Related Questions