You are on page 1of 5

Practical – 4

Aim :- Write an algorithm and find the efficiency of the same for following
problems.
a) Write a program to find the factorial by using Iterative approach.
#include<iostream>
using namespace std;
int main()
{
int n, fact = 1,i;
cout<<"Enter the Number:-";
cin>>n;
for(i=1;i<=n;i++)
{
fact = fact*i;
}
cout<<"Factorial of "<<n<<" is "<<fact;
return 0;
}

Output:-
b) Write a program to find the factorial by using Recursive approach.
#include<iostream>
using namespace std;
int fact(int n)
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
int main()
{
int n;
cout<<"Entre the Number:-";
cin>>n;
cout<<"Factorial of "<<n<<" is:-"<<fact(n);
return 0;
}

Output:-
c) Write a program to printing Fibonacci series by using Irerative approach.
#include<iostream>
using namespace std;
int main()
{
int n0=0,n1=1,n2,i,num;
cout<<"Enter the number of element:-";
cin>>num;
cout<<n0<<" "<<n1<<" ";
for(i=2;i<num;++i)
{
n2=n0+n1;
cout<<n2<<" ";
n0=n1;
n1=n2;
}
return 0;
}
d) Write a program to printing Fibonacci series by using Recursive approach.
#include<iostream>
using namespace std;
void fi bonaci(int n)
{
stati c int n1=0,n2=1,n3;
if(n>0)
{
n3=n1+n2;
n1=n2;
n2=n3;
cout<<n3<<" ";
fi bonaci(n-1);
}
}
int main()
{
int num;
cout<<"Enter the number:-";
cin>>num;
cout<<"0 "<<"1 ";
fi bonaci(num-1);
return 0;
}
Output:-

Conclusion:-
From this practi cal , we learn about Iterati ve and Recursive method. And
using this two method we fi nd Factorial and printi ng Fibonacci series.

You might also like