Simple C++ recursion code isn't working how I expected it to | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Simple C++ recursion code isn't working how I expected it to

#include <iostream> using namespace std; //a function using recursion to add up numbers in a sequence int add(int a) { if (a < 3) { return a + add(a+1); } else { return 0; // return 0 because otherwise it adds whatever other number to the total } } //how I expected it to run //1 + 2 (a = 1) //1 + 2 + 3(a = 2) //1 + 2 + 3 + 4(a = 3) int main() { cout << add(1); } Assigning 1 as a parameter returns 3, it seems as though the function only runs once where 1 is the parameter(return 1 + 2) Why isn't the function running a second time with 2 as a parameter?(where the total would be return 3(total so far) + 3(current parameter + 1) If I misunderstood something please let me know edit The code returns the desired output if i change the if statement to (a < 4), why?

3rd Jul 2017, 8:30 AM
Dima
7 Answers
+ 7
if you just want to do this 1 2 3 4 5 6 7 8 etc.. then you dont need to say a + add(a+1) . you can just say add(a+1). and instead of returning 0 when you hit the limit, return a
3rd Jul 2017, 9:20 AM
jay
jay - avatar
+ 6
it gets added. otherwise a would not increase in value
3rd Jul 2017, 9:13 AM
jay
jay - avatar
+ 6
huh, fair enough.. but that makes it more complicated...but ok.. still addition, not multiplication (see code)
3rd Jul 2017, 10:00 AM
jay
jay - avatar
0
This is what happen : add(1) 1<3 true return 1+add(2) <--1+2=3-- //// output 3 add(2) | 2<3 true | return 2+add(3) <-2+0=2-- add(3) | 3<3 false return 0 >--0--- Hope you'll understand, if you don't understand, I can try with sentence 😂 Ask me if you want anything !
3rd Jul 2017, 8:39 AM
Jojo
0
I may be messing up a bit, thanks for the answers but I have a slight feeling, true or not that the (+ add(a+1) isn't added to the total but only executed, so my code is run as: return a (a = 1) return a (a = 2) = 3
3rd Jul 2017, 8:58 AM
Dima
0
the a + add(a+!) was me making the lesson in recursion more simple by adding instead of multiplying, also I removed the factorial element completely
3rd Jul 2017, 9:57 AM
Dima