0

I made a very simple program to better grasp recursion but something is confusing me.

#include <iostream> using namespace std; //a function using recursion to add up numbers in a sequence int add(int a) { if (a == 1||a == 2) { return a + add(a+1); } else { return 1; } } int main() { cout << add(1); } Why is the output 4 rather than 6? In the first loop or "run" where a = 1, from my point of view it executes like so: return 1 + 2 = 3 The second and final loop where the parameter is 2: return 3 + 3(2+1) Apologies if my layout is confusing but please help

29th Jun 2017, 1:17 PM
Dima
2 odpowiedzi
0
1+ (1+2)
29th Jun 2017, 1:28 PM
Calviղ
Calviղ - avatar
0
1 + 2 + 1 1 and 2 are the values of a. When a become 3 the loop returns 1
29th Jun 2017, 3:53 PM
Andrés04_ve
Andrés04_ve - avatar