This works fine because we are using the prefix decrement operator in the recursive call !
public static void main(String[] args) {
doubt1(5);
}
Prefix Decrement:
static void doubt(int num)
{
if(num==0)
return;
System.out.println(num);
doubt(--num);
}
Postfix Decrement:
static void doubt1(int num)
{
if(num==0)
return;
System.out.println(num);
doubt1(num--);
}
But when we use the postfix decrement it can lead to stack over flow error , I understand why it's causing the error , but I want to know , if we use num-1 in the recursive call it doesn't give the overflow error , my question is -> why it's not giving the error coz it calculating the num-1 and passing the value to the recursive call but not calculating the num-- in the call ?
Want the explanation why it calculating the num-1 not num-- in the recursive call ? Not why it's happening !
doubt(num--)is same as callingdoubt(5), whereas both ofdoubt(num-1)anddoubt(--num)are the same as callingdoubt(4)and num inside the nested call is now 4... and so on