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:

  1. Start by subtracting K from N in each recursive call
  2. When N becomes negative or zero, flip the flag to start adding
  3. Continue adding K until we reach the original number
  4. 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

Number Series Generation Process Subtraction Phase (flag = True) 10 -4 6 -4 2 -4 -2 Switch! flag = False Addition Phase (flag = False) -2 +4 2 +4 6 +4 10 Legend: Subtraction Addition Switch Point End Point

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.

Updated on: 2026-03-25T06:24:34+05:30

813 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements