Question anna cole in lesson «Recursion: when a function calls itself», course «Programming fundamentals»
Hi! Thank you for such awesome lessons! This task is very tough, however. Even after looking at the teacher's solution I didn't understand the last part, namely, why we need 'end' in it?
return begin + sequenceSum(begin + 1, end);
I don't see how it's used in the function: we don't use it for addition. Could you please explain? Thank you!
Hey Anna,
glad you liked it!
Remember the concept of a terminating scenario from the video lesson? Basically, it's a condition of when to end recursion. Without such condition, the recursion will be endless, infinite. The function will never stop calling itself and eventually, the program will run out of memory and crash.
Even though end
isn't used in any additions or calculations, it is used for the terminating condition: check out line 6 of the solution. It says: when the recursive process hits this point (i.e. when begin
equals end
), the program returns begin
instead of making a recursive call. This will be the end of the series of the recursive calls.
And while begin
does not equal end
(see line 9), the recursive call is made. And this new call is made with begin + 1
. So, every new recursive step we increase the value of begin
and pass it along, until we hit the point where begin
is finally as big as end
.
Does it make things clearer?
Thank you! It helps a lot. I had this terminating concept at the back of my mind but simply didn't know how to put it in the code. Now I understand that it should be a part of the function, after a comma and in the brackets.
Thanks for the hard work building this learning platform, guys!
Use Hexlet to the fullest extent!
- Ask questions about the lesson
- Test your knowledge in quizzes
- Practice in your browser
- Track your progress
Sign up or sign in