Aditya Pandey
Aditya Pandey

Reputation: 11

i want print 1 to n number by help of recursion in java

public class Main {
    public static void main(String[] args) {
        print(10);
    }
    static void print(int s)
    {
        if (1==s) {
            System.out.print(s);
        }
        System.out.print(s);
        print(s-1);
    }
}

But I want output like this:

12345678910

Upvotes: 1

Views: 188

Answers (3)

Vasim Hayat
Vasim Hayat

Reputation: 929

Solution 1:- If you want the end result-oriented then you can try this

public static int doCalculaton(int numVal, int endVal) {
    System.out.println(endVal - numVal);
    if (numVal == 0) {
        return numVal;
    }
    return doCalculaton(numVal - 1, endVal);
}

public static void main(String[] args) {
    int toBeCalculateNum = 10;
    doCalculaton(toBeCalculateNum, toBeCalculateNum);
}

Solution 2:- If you want to use the result after calling

public static int doCalculaton(int numVal, ArrayList<Integer> numerList) {
        numerList.add(numVal);
        if (numVal == 0) {
            return numVal;
        }
        return doCalculaton(numVal - 1, numerList);
    }

    public static void main(String[] args) {
        ArrayList<Integer> numerList = new ArrayList<>();
        doCalculaton(10, numerList);
        Collections.reverse(numerList);
        System.out.println(numerList);

        // TODO loop and do whatever you want to do

    }

Upvotes: 0

Dorian Pavetić
Dorian Pavetić

Reputation: 105

Here, try this.

public static void main(String[] args) {
        print(1, 10);
}

static void print(int startValue, int endValue)
{
    System.out.print(startValue);
    if(startValue < endValue)
       print(startValue+1, endValue);
}

Upvotes: 1

Eran
Eran

Reputation: 393801

You existing recursion never ends. You should only make the recursive call if s >= 1.

And to print the numbers in increasing order, you need to first make the recursive call and then print the current number:

static void print(int s)
{
    if (s >= 1) {
      print(s-1);
      System.out.print(s);
    }
}

Upvotes: 2

Related Questions