![]() |
VOOZH | about |
Given two numbers N and K, the task is to print a number series where each term is obtained by repeatedly subtracting K from N until the number becomes zero or negative and once it becomes zero or negative, we start adding K back until the number reaches the original value N again. You must do this without using any loop.
For Example:
Input: N = 15, K = 5
Output: 15 10 5 0 -5 0 5 10 15Input: N = 20, K = 6
Output: 20 14 8 2 -4 2 8 14 20
Let's explore different methods to print number series without using loop in Python.
This method uses recursion to repeatedly subtract and add the number K. The same function calls itself until number becomes zero or negative and then reverses back to the original value, forming the full pattern automatically.
20 14 8 2 -4 2 8 14 20
Explanation:
This method introduces a flag variable to control whether the program should subtract or add K. Once the number becomes zero or negative, the flag flips, and the recursion direction reverses automatically.
20 14 8 2 -4 2 8 14 20
Explanation:
This method uses a lambda function (anonymous function) and Python’s recursive nature in a single line. It’s compact and demonstrates recursion elegantly.
20 14 8 2 -4 2 8 14 20
Explanation:
This method stores the entire recursive series inside a list and then prints it using the * unpacking operator for clean output.
20 14 8 2 -4 2 8 14 20
Explanation:
Please refer complete article on Print Number series without using any loop for more details!