Home > Mobile >  When I use "n--" instead of "n-1" why do I get stackoverflow error?
When I use "n--" instead of "n-1" why do I get stackoverflow error?

Time:06-28

In this code which is a program to print elements 1 to 5 recursively, when I use n-- instead of n-1, I am getting a stack overflow error. whereas when n-1 is used the code worked perfectly. shouldn't n-- and n-1 work the same in this code?

    //when using n--

    class PrintElements1to5
    {
        public static void main(String[] args)
        {
            recursivePrint(5);
        }
    
        static void recursivePrint(int n)
        {
            if(n<1)
                return;
            recursivePrint(n--);  
            System.out.print(n " ");
        }
    }

output:

Exception in thread "main" java.lang.StackOverflowError
    //when using n=n-1
    class PrintElements1to5
    {
        public static void main(String[] args)
        {
            recursivePrint(5);
        }
    
        static void recursivePrint(int n)
        {
            if(n<1)
                return;
            recursivePrint(n-1);
            System.out.print(n " ");
        }
    }

output:

1 2 3 4 5 

CodePudding user response:

n-- returns the value of n first, then decrement n. So in your case, it becomes an infinite loop because n is never changing. You can use --n instead which decrement n first, then returns the value of n. Let's take a simpler example.

int x = 3;
System.out.println(x - 1); // prints 2, x is still 3
System.out.println(x--);   // prints 3, x becomes 2
System.out.println(--x);   // prints 1, x becomes 1
  • Related