Method 1: Using the divide method
def sum_of_digit( n ): if n == 0: return 0 return (n % 10 + sum_of_digit(int(n / 10))) num = int(input("Enter the number whose sum of digits you want:")) result = sum_of_digit(num) print("Sum of digits of number",num,"is", result, "using recursion")
Output:
Enter the number whose sum of digits you want:3692
Sum of digits of number 3692 is 20 using recursion
Explanation:
Here we will be using conditional for checking that if the number is 0 then its sum will also be zero and so we checked whether n is equal to zero or not. If it is not, then we first divided our number will 10 and then added that with the output of the sum_of_digit() function. The call to this function again simply means that it is a recursive approach to solving this problem. Now, this function will again be called and the output of that will be added to the previously computed value in such a way it will continue till the number n is equal to zero. Now the final computed value is returned back and printed.
This is the one method to solve this problem recursively. Do share yours if you have any.
- Oracle Hiring for Python internship 2023: Apply Now
- Capgemini hiring freshers and experienced in bulk with CTC 5-15 LPA. Apply now!
- IIT Kanpur’s Python Learning Program: Apply Now
- Microsoft Giving Free Machine Learning Course: Enroll Now
- Accenture Giving Free Developer Certificate in 2023
- Microsoft Bing Eating Google Traffic: Check results here
- ChatGPT 4 with videos next week: Unveiled by Microsoft
- DevSecOps Internship at IBM: Apply Now
- Python Internship at Cisco: Apply Now
- Python Internship at HP: Apply Now
- Python | Asking the user for input until they give a valid response
- Python | How to iterate through two lists in parallel?
- Python Internship at Lenovo: Apply Now
- Amazon Summer Internship 2023
- Python | How to sort a dictionary by value?
- Amazon Giving Free Machine Learning Course with Certificate: Enroll Now
- Elon Musk hiring AI researchers to develop OpenAI rival
- Why Elon Musk Quits OpenAI?
- Google Summer Internship 2023
- Python | How to split a list into equally-sized chunks?
- 5 Secret ChatGPT skills to make money
- Python | Remove items from a list while iterating
- Free Google Certification Courses
- 5 AI tools for coders better than ChatGPT
- Python | How to get dictionary keys as a list
- New secrets to Earn money with Python in 2023
- Flower classification using CNN
- How to represent Enum in Python?
- 5 methods | Flatten a list of lists | Convert nested list into a single list in Python
- What does if __name__ == __main__ do in Python?