User1959
User1959

Reputation: 1

Change the order of a sequence

I am trying to print a sequence using recursion without a loop. Using the code below, I get the correct output; however, it goes from large to small, and I would like it to go from small to large. What would be the best way to do that? Currently I get the output:

22 19 16 13 10

but I would like it to be reversed.

public class Recursion
{
    public static void main(String[] args)
    {
        sequence(5);
    }

    public static void sequence(int n)
    {
        if (n >= 1)
        {
            int x = ((3*n) + 7);
            System.out.print(x + " ");
            sequence(n-1);
        }
    }
}

Upvotes: 0

Views: 292

Answers (2)

Stephen P
Stephen P

Reputation: 14800

Right now you print the computed value, and then you recurse with the next (decremented) n-value, which prints the next value in the sequence.

All you need to do is recurse first, and then print the current computed value after. This will print the "next" value of the sequence and then finish printing the just-computed "current" value.

public class Recursion
{
    public static void main(String[] args)
    {
        sequence(5);
        System.out.println();
    }

    public static void sequence(int n)
    {
        if (n >= 1)
        {
            int x = ((3*n) + 7);
            sequence(n-1);
            System.out.print(x + " ");  // changed order of recursive call and print
        }
    }
}

Upvotes: 4

Tushar
Tushar

Reputation: 657

You can use a collection and reverse method like below:

public static void main(String[] args) {
    List<Integer> sequence = new ArrayList<>();
    sequence(5,sequence);
    Collections.reverse(sequence);
    System.out.println(sequence);
  }

  public static void sequence(int n, final List<Integer> sequence) {
    if (n >= 1) {
      int x = ((3 * n) + 7);
      sequence.add(x);
      sequence(n - 1, sequence);
    }
  }

Output:

[10, 13, 16, 19, 22]

Upvotes: 0

Related Questions