0% found this document useful (0 votes)
58 views

Factorial Program Using Iterative and Recursive Method

The document discusses and compares the time complexity of calculating factorials using iterative and recursive methods. It includes code to implement functions for calculating factorials recursively and iteratively. The code takes a number as input, calculates the factorial of the number using both methods, and prints the results along with the time taken for each method.

Uploaded by

Manav Makwana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Factorial Program Using Iterative and Recursive Method

The document discusses and compares the time complexity of calculating factorials using iterative and recursive methods. It includes code to implement functions for calculating factorials recursively and iteratively. The code takes a number as input, calculates the factorial of the number using both methods, and prints the results along with the time taken for each method.

Uploaded by

Manav Makwana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Institute of Technology,

Computer Science and Engineering

Implementation and Time analysis of factorial


programs using iterative and recursive method.
INPUT:
// Implementation and Time analysis of factorial
// program using an iterative and recursive method.
#include <stdio.h>
#include <time.h>
long int fact(int n);
long int Ifact(int n);
int main(){
double time_rec=0.0;
double time_ite=0.0;
int num;
printf("Enter a number");
scanf("%d", &num);

printf("\n Using Recursion :: \n");


clock_t begin_rec=clock();
if(num<0)
printf("No factorial for negative number\n");
else
printf("Factorial of %d is %ld\n", num, fact(num));
clock_t end_rec=clock();
time_rec+=(double)(end_rec-begin_rec)/CLOCKS_PER_SEC;
printf("Time elapsed in recurion factorial is %f\n", time_rec);

printf("\n Using Iterative :: \n");

Enrolment number(180050131034) Page 1


Institute of Technology,
Computer Science and Engineering

clock_t begin_ite=clock();
if(num<0)
printf("No factorial for negative number\n");
else
printf("Factorial of %d is %ld\n", num, Ifact(num));
clock_t end_ite=clock();
time_ite+=(double)(end_ite-begin_ite)/CLOCKS_PER_SEC;
printf("Time elapsed in iterative factorial is %f", time_ite);

return 0;
}

long int fact(int n){


if(n==0)
return(1);
return(n*fact(n-1));
}

long int Ifact(int n){


long fact=1;
while(n>0){
fact*=n;
n--;
}
return fact;
}

Enrolment number(180050131034) Page 2


Institute of Technology,
Computer Science and Engineering

OUTPUT:

Enrolment number(180050131034) Page 3

You might also like