Recursion with Double Call (C++) -
can please explain me how adds 26?
i confused 'double call'. maybe don't understand recursion think do.
#include <iostream> using namespace std; int rec(int * n, int max) { if (max < 0) return 0; return n[max] + rec(n, max - 1) + rec(n, max - 2); } int main() { const int max = 5; int n[] = { 1, 2, 3, 4, 5 }; int f = rec(n, max - 1); cout << f << endl; return 0; }
int f = rec(n, 4) = n[4] + rec(n, 3) + rec(n, 2) = 5 + (n[3] + rec(n, 2) + rec(n, 1)) + (n[2] + rec(n, 1) + rec(n, 0)) = 5 + (4 + (n[2] + rec(n, 1) + rec(n, 0)) + (n[1] + rec(n, 0) + rec(n, -1)) + (3 + (n[1] + rec(n, 0) + rec(n, -1)) + (n[0] + rec(n, -1) + rec(n, -2))) = 5 + (4 + (3 + rec(n, 1) + rec(n, 0)) + (2 + rec(n, 0) + 0) + (3 + (2 + rec(n, 0) + 0) + (1 + 0 + 0)) = 5 + (4 + (3 + (n[1] + rec(n, 0) + rec(n, -1)) + (n[0] + rec(n, -1) + rec(n, -2))) + (2 + (n[0] + rec(n, -1) + rec(n, -2)) + 0) + (3 + (2 + (n[0] + rec(n, -1) + rec(n, -2)) + 0) + 1) = 5 + (4 + (3 + (2 + (n[0] + rec(n, -1) + rec(n, -2)) + 0) + (1 + 0 + 0)) + (2 + (1 + 0 + 0) + 0) + (3 + (2 + (1 + 0 + 0) + 0) + 1)) = 5 + (4 + (3 + (2 + (1 + 0 + 0) + 0) + 1) + (2 + 1 + 0) + (3 + (2 + 1 + 0) + 1)) = 5 + (4 + (3 + (2 + 1 + 0) + 1) + 3 + (3 + 3 + 1)) = 5 + (4 + (3 + 3 + 1) + 3 + 7) = 5 + (4 + 7 + 10) = 5 + 21 = 26
and suggested above, following code generates entire expression that, when evaluated, equals 26. can played generate step-by-step work.
#include <iostream> #include <string> using namespace std; string rec(string * n, int max) { if (max < 0) return "0"; auto = rec(n, max - 1), b = rec(n, max - 2); return "(" + n[max] + " + " + + " + " + b + ")"; } int main() { const int max = 5; string n[] = { "1", "2", "3", "4", "5" }; auto f = rec(n, max - 1); cout << f << endl; return 0; }
Comments
Post a Comment