-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion.cpp
More file actions
49 lines (38 loc) · 996 Bytes
/
Recursion.cpp
File metadata and controls
49 lines (38 loc) · 996 Bytes
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
#include <iostream>
void walk(int steps);
int factorial(int num);
int main()
{
// recursion = a programming technique where a function invokes itself from within
// break a complex concept into repeateble single steps
// Func invokes itself from within
// iterative vs recursive
// advantages = less code and its cleaner, useful for sorting and searcing algs
// disadvantages = uses more memory and is slower
walk(100);
int num;
std::cout << "enter a number to get its factorial: ";
std::cin >> num;
std::cout << factorial(num);
return 0;
}
void walk(int steps)
{
//iterative: for(int i = 0; i < steps; i++)
if(steps > 0)
{
std::cout << "You take a step\n";
walk(steps - 1); //recursive, if caught in infinite loop you will cause stack overflow
}
}
int factorial(int num)
{
if(num > 1)
{
return num*factorial(num-1);
}
else
{
return 1;
}
}