SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
5.recursion
Exercise:
Programming Excercises
Question:1 | ISBN:978013274719 | Edition: 6

Question

(Sum the digits in an integer using recursion) Write a recursive function that computes the sum of the digits in an integer. Use the following function header:
def sumDigits(n):
For example, sumDigits(234) returns 2+3+4 = 9 Write a test program that prompts the user to enter an integer and displays its sum.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

A test program that prompts the user to enter an integer and displays its sum:

Code :

def sumDigits( n ):        #defining a function sumDigits
    if n == 0:             #check whether n is equal to 0 are not
        return 0           # if yes,return 0
    return (n % 10 + sumDigits((n // 10)))    #else return sum of its digits
num = int(input("enter an integer:"))         #take input num value
result = sumDigits(num)                       #using sumDigits function
print("Sum of digits in",num,"is", result)     #print the sum

Output:

enter an integer:234
Sum of digits in 234 is 9


enter an integer:0
Sum of digits in 0 is 0




enter an integer:6455
Sum of digits in 6455 is 20

 

0 0

Discussions

Post the discussion to improve the above solution.