Professional Documents
Culture Documents
Lecture 16 Staticvariable Recursion Stds
Lecture 16 Staticvariable Recursion Stds
int globalVar;
void showLocal();
void showStatic();
int main()
{
cout << "GlobalVar:" << globalVar << endl;
return 0;
}
void showLocal()
{
int localNum = 0; // local variable life and visibility only within function
cout << localNum << endl;
localNum++;
}
void showStatic()
{
static int statNum = 0; // static local variable// life like global variable and
visibility like local variable
cout << statNum << endl;
statNum++;
}
Ouput:
GlobalVar: 0
showLocal() local variable values :
0
0
0
0
0
showStatic() static variable values :
0
1
2
3
4
Recursive function:
1. Elegant code as it matches with the recursive patterns
2. Whereas the Iterative code is efficient
5! = 5* 4*3*2*1
5! = 5* 4!
4! = 4* 3! //1. calling again and again
3! = 3* 2!
2! = 2* 1!
1! = 1* 0!
0! = 1 //2. base case
}
return fact;
}
int main()
{
cout << NonRecursivefactorial(5) << endl;
cout << factorial(5) << endl;;
}
Homework2
X5 = X* X *X* X * X
X5 = X* X4
X4 = X* X3
X3 = X* X2
X2 = X* X1
X1 = X* X0
X0 = 1
Xn = X* Xn-1
/*
double raisToPow(double n, int p)
{
double res = 1.0;
for(int i = p; i>0; i--)
{
res = res * n;
}
return res;
}
*/
//recursive implementation
double raisToPow(double n, int p)
{
// HOME WORK 2… PROVIDE ITS IMPLEMENTATION
}
Write the implementation of void displayHello(int i) that prints the hello message 10 times
recursively.
void displayHello(int i)
{
int main()
{
displayHello(1);
return 0;
}
Output sample:
1 Hello world
2 Hello world
3 Hello world
4 Hello world
5 Hello world
6 Hello world
7 Hello world
8 Hello world
9 Hello world
10 Hello world
int fibonacci(int n) {
int a = 0, b = 1, c;
if (n == 0)
return a;
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
int main() {
int n;
cout << "Enter the number of terms for Fibonacci series: ";
cin >> n;
cout << "Fibonacci series up to " << n << " terms:" << endl;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
return 0;
}
Sample output:
Fibonacci series up to 10 terms:
0 1 1 2 3 5 8 13 21 34
NOTE: for all three task, you need to provide the trace the recursive call using
both tree graph/tree structure and also using Stack