Professional Documents
Culture Documents
Practical 1
Aim: Implement and analyze the algorithms given below.
1.1 Factorial of a given number (Iterative and Recursive)
Program:
[Iterative]
#include <iostream>
using namespace std;
int c=0;
int fact(int n) {
c++;
if ((n==0)||(n==1)){
c++;
return 1;
}
else{
c++;
c++;
c++;
return n*fact(n-1);
}
}
int main() {
int n;
cin>>n;
c++;
cout<<"Factorial of "<<n<<" is "<<fact(n)<<endl;;
c++;
cout<<"Counter: "<<c<<endl;
return 0;
}
Output:
Analysis Table:
Input Output
5 18
10 33
15 48
20 63
25 78
30 93
Graph:
Factorial (Iterative)
100
90 y = 3x + 3
80
70
60
50
40
30
20
10
0
0 5 10 15 20 25 30 35
Program:
[Recursive]
#include <iostream>
using namespace std;
int c = 0;
int fact(int n)
{
c++;
if ((n == 0) || (n == 1))
{
c++;
return 1;
}
else
{
c++;
c++;
c++;
return n * fact(n - 1);
}
}
int main()
{
int n;
cin >> n;
c++;
cout << "Factorial of " << n << " is " << fact(n) << endl;
;
c++;
cout << "Counter: " << c << endl;
return 0;
}
Output:
Analysis Table:
Input Output
5 20
10 40
15 60
20 80
25 100
30 120
Graph:
Factorial (Recursive)
140
120 y = 4x
100
80
60
40
20
0
0 5 10 15 20 25 30 35
Program:
[Iterative]
#include <iostream>
using namespace std;
int main()
{
int n, t1 = 0, t2 = 1, nextTerm = 0, cnt = 0;
cnt++;
Output:
Analysis Table:
Input Output
5 19
10 34
15 49
20 64
25 79
30 94
Graph:
Fibonacci Sequence (iterative)
100
y = 3x + 4
80
60
40
20
0
0 5 10 15 20 25 30 35
Program:
[Recursive]
#include <iostream>
using namespace std;
int c = 0;
int fib(int x)
{
c++;
if ((x == 1) || (x == 0))
{
c++;
return (x);
}
else
{
c++;
c++;
c++;
c++;
return (fib(x - 1) + fib(x - 2));
}
}
int main()
{
int x, i = 0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
c++;
while (i < x)
{
c++;
cout << " " << fib(i);
c++;
i++;
c++;
}
c++;
c++;
cout << endl
<< "counter : " << c;
return 0;
}
Output:
Analysis Table:
Input Output
5 77
10 984
15 11145
20 12933
25 1374872
30 15248099
Graph:
15000000
10000000
y = 459220x - 5E+06
5000000
0
0 5 10 15 20 25 30 35
-5000000
Program:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the size of Array: ";
cin >> n;
int arr[n], i, num, index, cnt = 0;
cnt++;
cout << "Enter numbers:";
for (i = 0; i < n; i++)
cin >> arr[i];
cout << "\nEnter a Number to Search: ";
cin >> num;
cnt++;
for (i = 0; i < n; i++)
{
cnt++;
cnt++;
if (arr[i] == num)
{
index = i;
cnt++;
break;
}
cnt++;
}
cnt++;
cout << "\nFound at Index No." << index;
cout << endl;
cnt++;
cout << "Count:"
<< cnt;
return 0;
}
Output:
Analysis Table:
Graph:
Linear Search
40
y = 6x + 7
30
20 y = 3x + 4
10
y=7
0
3 5 7 9 11
Complexity:
Conclusion:
Here, in this practical we were able to learn about the Best, Average and Worst Case Scenario
about Linear Search, Fibonacci Series and Factorial of the given number.
And on drawing the graph we can clearly understand that in Linear Search we saw the best case
for linear line.