Home > Back-end >  Recursive function to print all numbers in ascending order up to the given entered number
Recursive function to print all numbers in ascending order up to the given entered number

Time:04-10

I've got everything working for positive integers, but can't figure out how to do it with negative integers. It prints it from the biggest value to the smallest. I want it to be the same with the positive integers, from smallest value to biggest.

import java.util.Scanner;

public class Ascending {
public static void ascendingorder(int n){
if (n > 0) {
ascendingorder(n - 1);
System.out.print(n   " ");
}
        else if(n < 0){
        ascendingorder(n   1);
                System.out.print(n   " ");
                }
}
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an Integer Number: ");
        int n = in.nextInt();
        ascendingorder(n);
        System.out.println();
    }
}

CodePudding user response:

if I understood your question, the answer could be just to invert lines in the else if statement:

ascendingorder(n   1);
System.out.print(n   " ");

So it would be

System.out.print(n   " ");
ascendingorder(n   1);

CodePudding user response:

Same observation found you just need to write print statement first before calling recursion for negative integers

CodePudding user response:

In this case you function add 1 until n becomes 0. Then it prints valeue from 0 to n. In order to prevent it you should print n first then you shoud increase it's value.

  • Related