Website Summary Files Commits Branches @commit @diff @stats
path: root / Seminar02 / recursion.cpp
diff options
context:
space:
mode:
Commit51d955fbdada4400c8efd504d637b4ece6fcee22 (patch)
Author
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-10-12 15:42:41 +0300
Committer
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-10-12 15:42:41 +0300
Filese029d2772c32e4cce968faf6940f1b5bde46f0cc /Seminar02/recursion.cpp
Data-structures-and-algorithms-51d955fbdada4400c8efd504d637b4ece6fcee22.tar
Data-structures-and-algorithms-51d955fbdada4400c8efd504d637b4ece6fcee22.tar.gz
Data-structures-and-algorithms-51d955fbdada4400c8efd504d637b4ece6fcee22.zip
Parentfd8930b9c939f3b234b7fe661f329004a931b79c (diff)
add seminar02
1 files changed, 33 insertions, 0 deletions
-rw-r--r--Seminar02/recursion.cpp33
diff --git a/Seminar02/recursion.cpp b/Seminar02/recursion.cpp
new file mode 100644
index 0000000..63f4aa0
--- /dev/null
+++ b/Seminar02/recursion.cpp
@@ -0,0 +1,33 @@
+#include<iostream>
+#include<stack>
+
+int fib(unsigned x) {
+ if(x == 0 || x == 1)
+ return 1;
+
+ return fib(x - 1) + fib(x - 2);
+}
+
+// Малък пример как можем да симулираме рекурсия чрез стек.
+int fibStack(unsigned x) {
+ std::stack<unsigned> s;
+ s.push(x);
+ int result = 0;
+
+ while(!s.empty()) {
+ int currArg = s.top();
+ s.pop();
+
+ if(currArg == 1 || currArg == 0)
+ ++result; // Еквивалентно на return 1;
+ else{
+ s.push(currArg - 1); // Еквивалентно на fib(x - 1);
+ s.push(currArg - 2); // Еквивалентно на fib(x - 2);
+ }
+ }
+ return result;
+}
+
+int main() {
+ std::cout << fib(10) << " " << fibStack(10);
+}