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
Selected Reading
Python Program for Print Number series without using any loop
In this article, we will learn how to print a number series without using any loop. We'll use recursion to subtract and add values alternately until we return to the original number.
Problem statement ? Given two numbers N and K, subtract K from N until N becomes negative or zero, then start adding K until we reach the original number N again.
Example Output
N = 10, K = 4 Output: 10 6 2 -2 2 6 10
Algorithm
The approach uses recursion with a flag to control the direction:
- Start by subtracting K from N in each recursive call
- When N becomes negative or zero, flip the flag to start adding
- Continue adding K until we reach the original number
- Use a boolean flag to switch between subtraction and addition
Implementation
def print_number_series(n, original, k, flag):
# Print current number
print(n, end=" ")
# If number becomes negative or zero, switch direction
if n <= 0:
if flag == 0:
flag = 1
else:
flag = 0
# Stop when we return to original number during addition phase
if n == original and not flag:
return
# Subtract K when flag is True
if flag:
print_number_series(n - k, original, k, flag)
return
# Add K when flag is False
if not flag:
print_number_series(n + k, original, k, flag)
return
# Test the function
n = 10
k = 4
print_number_series(n, n, k, True)
10 6 2 -2 2 6 10
How It Works
Key Points
- Uses recursion instead of loops to generate the series
- The flag parameter controls whether to subtract or add K
- Direction switches when N becomes negative or zero
- Stops when returning to the original number during addition phase
Conclusion
This recursive approach demonstrates how to generate a number series without loops. The key is using a flag to control the direction and proper termination conditions to avoid infinite recursion.
Advertisements
