Print m multiplies of n without using any loop in Python.

Given a number n, we can print m multiples of a step value without using any loop by implementing a recursive function. This approach uses function calls to simulate iteration.

Problem Statement

We need to print numbers starting from n, decreasing by a step value until we reach 0 or negative, then increasing back to the original number.

Example

Input: n = 15, step = 5
Output: 15 10 5 0 5 10 15

Algorithm

The recursive approach works as follows:

  1. Start with the given number n and a flag indicating direction
  2. Print the current number
  3. If moving down (flag = True) and number > 0, subtract step and continue
  4. If moving down and number ? 0, change direction (flag = False)
  5. If moving up (flag = False), add step until we reach original number
  6. Stop when we return to the starting number while moving up

Implementation

def print_multiples(original_n, current_n, flag):
    print(current_n)
    
    # Base case: if moving back up and reached original number
    if flag == False and original_n == current_n:
        return
    
    if flag:  # Moving down
        if current_n - 5 > 0: 
            print_multiples(original_n, current_n - 5, True)
        else:  # Change direction when reaching 0 or negative
            print_multiples(original_n, current_n - 5, False)
    else:  # Moving up
        print_multiples(original_n, current_n + 5, False)

# Driver Code
n = 15
print_multiples(n, n, True)
15
10
5
0
5
10
15

How It Works

The function uses three parameters:

  • original_n: The starting number to return to
  • current_n: The current number being processed
  • flag: Direction indicator (True = decreasing, False = increasing)

The recursion creates a pattern where numbers decrease until reaching 0, then increase back to the original value.

Alternative Example

def print_pattern(original, current, going_down):
    print(current)
    
    if not going_down and current == original:
        return
    
    if going_down:
        if current - 3 >= 0:
            print_pattern(original, current - 3, True)
        else:
            print_pattern(original, current - 3, False)
    else:
        print_pattern(original, current + 3, False)

# Example with different step
n = 12
print_pattern(n, n, True)
12
9
6
3
0
3
6
9
12

Conclusion

Recursive functions can effectively replace loops for pattern generation. The key is using proper base cases and direction flags to control the recursive flow and create the desired number sequence.

---
Updated on: 2026-03-24T20:56:46+05:30

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements