Question anna cole in lesson «Recursion: when function calls itself», course «Intro to Programming»

anna cole

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!

2 0

R. D.

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?

1

anna cole

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!

0

Используйте Хекслет по максимуму!

  • Задавайте вопросы по уроку
  • Проверяйте знания в квизах
  • Проходите практику прямо в браузере
  • Отслеживайте свой прогресс

Sign up or sign in

By sending the form, you agree to "Personal Policy" and "Service Conditions".