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.
- Unveiling the Future of AI Detector
- CodeWithHarry Earns 20 Lakhs per month from YouTube?
- Cleaning Service Booking System in Python Tkinter
- Farmers Ecommerce App using Python Tkinter
- Guidelines for Project Collaboration Process
- The system of the binary conversion
- What is web development for beginners?
- Guide to Proxy Servers: How They Work and Why You Need Them?
- Python | Check Armstrong Number using for loop
- Python | Factorial of a number using for loop
- Link in bio
- Microsoft Giving Free Machine Learning Course: Enroll Now
- Accenture Giving Free Developer Certificate in 2023
- Python | Asking the user for input until they give a valid response
- Python | How to iterate through two lists in parallel?
- Amazon Summer Internship 2023
- Python | How to sort a dictionary by value?
- Amazon Giving Free Machine Learning Course with Certificate: Enroll Now
- 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?