lundi 22 juillet 2019

How does this function prints 1 2 3 4 5 in ascending order

I tried searching the answer but was not able to get any convincing answer. Can someone please explain me how does this c++ code prints 1 2 3 4 5 ?

I understood uptill the point when n=1. when n=1, fun(n-1) = fun(1-1) = fun(0) is not executed as n>0 is not satisfied , hence now cout << n << endl will be executed and n is still equal to 1 but then after printing 1 it should stop ?. How does it goes to the previous calls ??. How does it prints 2 3 4 5 ??

Also when cout <

#include <iostream>

using namespace std;

void fun(int n)
{
if(n>0)
 {
   fun(n-1);
   cout <<n<<endl;

 }
}

int main()
 {

   int x=5;
   fun(x);
 }

The above code prints 1 2 3 4 5 while from my understanding it should only print 1

Aucun commentaire:

Enregistrer un commentaire