Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Print Numbers in a Range (1,upper) Without Using any Loops
When it is required to print numbers in a given range without using any loop, we can use recursion. This technique involves defining a function that calls itself with a decremented value until it reaches the base case.
Below is the demonstration of the same ?
Example
def print_nums(upper_num):
if(upper_num > 0):
print_nums(upper_num - 1)
print(upper_num)
upper_lim = 6
print("The upper limit is :")
print(upper_lim)
print("The numbers are :")
print_nums(upper_lim)
Output
The upper limit is : 6 The numbers are : 1 2 3 4 5 6
How It Works
The function uses recursion to achieve the loop-like behavior:
The function
print_numschecks if the number is greater than 0If true, it calls itself with
upper_num - 1This continues until the base case (upper_num = 0) is reached
Then it prints the numbers in ascending order as the recursion unwinds
Alternative Implementation
You can also print numbers in descending order by placing the print statement before the recursive call ?
def print_nums_desc(upper_num):
if(upper_num > 0):
print(upper_num)
print_nums_desc(upper_num - 1)
upper_lim = 5
print("Numbers in descending order:")
print_nums_desc(upper_lim)
Numbers in descending order: 5 4 3 2 1
Conclusion
Recursion provides an elegant way to print numbers in a range without using loops. The key is understanding how the recursive calls stack and unwind to achieve the desired output order.
