Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 15 - Recursion - Section 15.3 - Case Study: Computing Fibonacci Numbers - Check Point - MyProgrammingLab - Page 505: 15.8

Answer

Program 1: Output is 15 program 2: Output: is 7 6 5 4 3 2 1

Work Step by Step

Program 1: Base case: n == 1 Recursive calls: f(n - 1) Explanation: The function f recursively adds the previous numbers to the current number until the base case of n == 1 is reached. In this case, the function is called with f(5), which leads to the following recursive calls: f(5) = 5 + f(4) f(4) = 4 + f(3) f(3) = 3 + f(2) f(2) = 2 + f(1) f(1) = 1 The final result is the sum of all these numbers, which is 15. Program 2 : Base case: n <= 0 Recursive calls: f(n // 10) Explanation: The function f recursively prints the last digit of a number and then calls itself with the remaining digits until there are no more digits left. In this case, the function is called with f(1234567), which leads to the following recursive calls: f(1234567) prints 7 and calls f(123456) f(123456) prints 6 and calls f(12345) f(12345) prints 5 and calls f(1234) f(1234) prints 4 and calls f(123) f(123) prints 3 and calls f(12) f(12) prints 2 and calls f(1) f(1) prints 1 and then returns. The digits are printed in reverse order, which is the expected behavior when working with integers.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.