-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17recursion.cpp
More file actions
56 lines (52 loc) · 1 KB
/
Copy path17recursion.cpp
File metadata and controls
56 lines (52 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream>
using namespace std;
int factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else if(n < 0)
{
return 0;
}
else
{
return n * factorial(n-1);
}
}
int fibonacci(int n)
{
if (n == 0 || n == 1)
{
return n;
}
else
{
return fibonacci(n-1) + fibonacci(n-2);
}
}
//Iterative approach is when the program is broken into simple operation codes
int fib_iterative(int n)
{
int a = 0;
int b = 1;
for (int i = 0; i < n-1; i++)
{
b = a + b;
a = b - a;
}
return a;
}
int main()
{
//Recursions are functions that perform a task in broken down steps
//for example a factorial function
int num;
cout<<"Enter a num"<<endl;
cin>>num;
cout<<"Factorial of "<<num<<" is "<<factorial(num)<<endl;
cout<<"Fibonacci sequence of "<<num<<" is "<<fibonacci(num)<<endl;
cout<<"Fibonacci sequence of "<<num<<" is "<<fib_iterative(num)<<endl;
return 0;
}