Ask Question

Write a recursive function named sumSquares that returns the sum of the squares of the numbers from 1 to num, in which num is a nonnegative int variable. Do not use global variables; use the appropriate parameters. Also write a program to test your function.

+5
Answers (1)
  1. 21 October, 23:16
    0
    def sumSquares (num):

    if (num = = 0):

    return 0

    else:

    return num*num + sumSquares (num-1)

    print (sumSquares (7))

    Explanation:

    * The code is in Python

    The function takes one parameter num. If the num is equal to 0, that means function checked all the numbers up until num, and stops.

    If the num is not equal to 0, the function will calculate the square of the number. It multiplies the num with num, adds this multiplication to result of the same function with a parameter that is decreased by 1.

    For example, if num is equal to 3 initially, following will happen:

    first iteration: sumSquares (3) = 3x3 + sumSquares (2)

    second iteration: sumSquares (2) = 2x2 + sumSquares (1)

    third iteration: sumSquares (1) = 1x1 + sumSquares (0)

    forth iteration : sumSquares (0) = 0

    If you go from bottom to top,

    We know that sumSquares (0) is equal to 0, that means the result of the third iteration is 1, 1 + 0

    We know that sumSquares (1) is equal to 1, that means the result of the third iteration is 5, 4 + 1

    We know that sumSquares (2) is equal to 5, that means the result of the third iteration is 14, 9 + 5
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a recursive function named sumSquares that returns the sum of the squares of the numbers from 1 to num, in which num is a nonnegative ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers