You are on page 1of 6

FACULTY OF ENGINEERING

Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

Experiment 5

Enrollment no: Batch: Page no:


FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

5. Implementation and Time analysis of factorial program using iterative


and recursive method.

A. Iteractive Method

Algorithm:

 Start program

 Ask the user to enter an integer to find the factorial

 Read the integer and assign it to a variable

 From the value of the integer up to 1, multiply each digit and update the
final value

 The final value at the end of all the multiplication till 1 is the factorial

 End program

Code:

#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number:
"); scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}

Enrollment no: Batch: Page no:


FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

Output

Time Complexity:
o Best case: O (n)
o Worst case: O (n)
o Average case: O (n)

Enrollment no: Batch: Page no:


FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

B. Recursive Method

Algorithm:

Step 1: Start

Step 2: Read number n

Step 3: Call factorial

(n) Step 4: Print

factorial f Step 5: Stop

factorial (n)

Step 1: If n==1 then return 1

Step 2: Else f=n*factorial (n-1)

Step 3: Return f

Code:

#include<stdio.h>

long factorial(int

n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
Enrollment no: Batch: Page no:
FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual
}

Enrollment no: Batch: Page no:


FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

void main()
{
int number;
long fact;
printf("Enter a number:
"); scanf("%d",
&number);

fact = factorial(number);
printf("Factorial of %d is %ld\n", number,
fact); return 0;
}

Output

Time Complexity:
o Best case: O (n)
o Worst case: O (n)
o Average case: O (n)

Enrollment no: Batch: Page no:

You might also like