Recursion

#include<stdio.h>
int fun(int a)
{
if(a==2)
printf("%d",a);
else
{
fun(--a);
}
printf("%d",a);
return 0;
}

int main()
{
clrscr();
fun(5);
getch();
return 0;
}

Output=22234
why is it so...???why three times 2
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

void fun(int a)
{
    if(a==2)
        std::cout << a;
    else
        fun(--a);

    std::cout << a;
}

int main()
{
    fun(5);

    std::cin.get();
    return 0;
}


Lets go through the code step by step shall we?
1. fun(5) is called, a == 5. a != 2. a == 4, call fun(4)
2. fun(4) is called, a == 4, a != 2, a == 3, call fun(3)
3. fun(3) is called, a == 3, a != 2, a == 2, call fun(2)
4. fun(2) is called, a == 2, print value of 'a' ((2)), recursive calling ends, print 'a' ((2))
5. return to fun(3), print value of 'a' ((2))
6. return to fun(4), print value of 'a' ((3))
7. return to fun(5), print value of 'a' ((4)).
8. Program terminates.
Topic archived. No new replies allowed.