You are on page 1of 5

ADA-LAB Poradhiya Chirag I

En.no:180280107082

Practical-4:Implementation and time analysis of factorial


program using iterative and recursive method:-
1)Using recursive method:

Input code:
#include<stdio.h>
int factorial_recursive(n){
if (n>=1)
return n*factorial_recursive(n-1);
else
return 1;
}
void main(){
int n;
printf(“Enter the number:”);
scanf(“%d,&n”);
printf(“factorial of %d is %d”,n,factorial_recursive(n));
}

Computer Department
L D College of Engineering Page 1
ADA-LAB Poradhiya Chirag I
En.no:180280107082

Output snapshot:

Time analysis:
Yes, the algorithm is linear in O(n) time, this is the case because it executes
once every time it decrements the value n and it decrements n until it reaches 0,
meaning the function is called recursively n times. This is assuming that both
decrementing and multiplication are constant operations.

Computer Department
L D College of Engineering Page 2
ADA-LAB Poradhiya Chirag I
En.no:180280107082

2)Using iterative method:

Input code:
#include<stdio.h>
int n,i,sum=1;
int factorial_iterative(n){
if (n=0)
return 1;
else{
while(n>0){
sum=sum*n;
n--;}
}
}
void main(){
printf(“enter the number:”);
scanf(“%d,&n”);
printf(“factorial of %d is %d”,n,factorial_iterative(n));
}

Computer Department
L D College of Engineering Page 3
ADA-LAB Poradhiya Chirag I
En.no:180280107082

Output snapshot:

Time analysis:
for the time complexity of the iterative solution, you have n multiplication in the
while loop, so a loose bound will be O(n). Every other operation can be
assumed to be unit time or constant time, with no bearing on the overall
efficiency of the algorithm.

Computer Department
L D College of Engineering Page 4
ADA-LAB Poradhiya Chirag I
En.no:180280107082

*****

Computer Department
L D College of Engineering Page 5

You might also like