- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Find Sum of Natural Numbers Using Recursion in Python?
If a function calls itself, it is called a recursive function. In order to prevent it from falling in infinite loop, recursive call is place in a conditional statement.
Following program accepts a number as input from user and sends it as argument to rsum() function. It recursively calls itself by decrementing the argument each time till it reaches 1.
def rsum(n): if n <= 1: return n else: return n + rsum(n-1) num = int(input("Enter a number: ")) ttl=rsum(num) print("The sum is",ttl)
Sample run of above program prints sum o natural numbers upto input number
Enter a number: 10 The sum is 55
Advertisements