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.
- Simple Code to compare Speed of Python, Java, and C++?
- Falling Stars Animation on Python.Hub October 2024
- Most Underrated Database Trick | Life-Saving SQL Command
- Python List Methods
- Top 5 Free HTML Resume Templates in 2024 | With Source Code
- How to See Connected Wi-Fi Passwords in Windows?
- 2023 Merry Christmas using Python Turtle
- 23 AI Tools You Won’t Believe are Free
- Python 3.12.1 is Now Available
- Best Deepfake Apps and Websites You Can Try for Fun
- Amazon launched free Prompt Engineering course: Enroll Now
- 10 GitHub Repositories to Master Machine Learning
- Hello World in 35 Programming Languages
- How to Scrape Data From Any Website with Python?
- Become Job Ready With Free Harvard Computer Science course: Enroll Now
- Free Python Certification course from Alison: Good for Resume
- Download 1000+ Projects, All B.Tech & Programming Notes, Job, Resume & Interview Guide, and More – Get Your Ultimate Programming Bundle!
- Udacity Giving Free Python Course: Here is how to Enroll
- Love Babbar’s Income Revealed
- Top 5 Websites to Learn Programming in 2024
- Python Internship for college students and freshers: Apply Here
- Microsoft Giving Free Python Course in 2023: Enroll Now
- Top 5 Free Python Courses on YouTube in 2024
- Complete Python Roadmap for Beginners in 2024
- New secrets to Earn money with Python in 2024
- Connect with HR Directly – Job Hack
- Google offering free Python course: Enroll Today
- What is an AI Tool?
- Google Internship 2024
- TCS Launched Free Certification Course with Industry Recognized Value