Tuesday, October 27, 2009

Recursive Function with static variable:

#include < stdio.h >
static int count;
void f(int n)
int i;
for(i =1;i<=n;i++)


How it works?
In this program we use recursive function (A function call itself is called as Recursive Function). Read with concentration or see the figure concentration otherwise you can’t understand what I’m trying to say,
At First F(3) will be called. Now n=3
I=1 n=3 1<=3(true) so it will call itself with n-i value f(2) will be called. Now this f(2) will be start to execute now n=2
I=1 n=2 1<=2 it’ll call f(1) .
Now f(1) will start to execute n=1
I=1 n=1 1<=1(true) it’ll call f(0)
F(0) will start to execute n=0
I=1 n=0 1<=0(false) so count will be increased count=1
Now it’ll back to f(1) function
In f(1) function i=2 n=1
so 2<=1(false) so count will be increased count=2
now it’ll back to f(2) function
i=2 n=2 2<=2(true) it’ll call the f(0) function again
in f(0) function i=1 n=0 1<=0(false) so count=3
It’ll back to f(2) function like this it’ll go back to f(3) function.

Understand Easily using turbo c compiler
I Think so you may confuse with this program. Ok I’ll guide you how to get understand easily using turbo c compiler.

Type the coding in compiler. Compile it . click on which variables values you want to know at run time. You can see the changes of values in variables at run time. Follow the procedure to see variable value at run time.

Move cursor to variable(which one you want to know the value at run time) press ctrl+F7. now small window(like warning window) will open in compiler it shows variable name as “undefined variable”. Now press F7 which will run the c program step by step. Now you can also get how the function is called. Like this you can easily understand the c program.

click on the picture to maximize


Post a Comment