C program to print number series without using any loop

In this problem, we are given two numbers N and K. Our task is to create a program that will print number series without using any loop.

The series starts from N and subtracts K until it becomes zero or negative. After that, we start adding K to it until it becomes N again. We cannot use any type of loop for this process.

Syntax

void printSeries(int current, int n, int k, int flag);

Input/Output Example

Input: n = 12, k = 3
Output: 12 9 6 3 0 3 6 9 12

To solve this problem without using a loop we will use recursion. We create a recursive function that calls itself and keeps track of whether to subtract or add K using a flag variable.

Example

Here's the C program to print number series using recursion −

#include <stdio.h>

void printSeries(int current, int n, int k, int flag) {
    printf("%d ", current);
    
    /* If current becomes 0 or negative, change direction */
    if (current <= 0)
        flag = 0;  /* Start adding */
    
    /* If we reach back to original n while adding, stop */
    if (current == n && flag == 0)
        return;
    
    /* If flag is 1, subtract k (going down) */
    if (flag == 1)
        printSeries(current - k, n, k, flag);
    /* If flag is 0, add k (going up) */
    else
        printSeries(current + k, n, k, flag);
}

int main() {
    int n = 12, k = 4;
    printf("The series is: ");
    printSeries(n, n, k, 1);  /* Start with flag = 1 (subtract) */
    printf("<br>");
    return 0;
}

Output

The series is: 12 8 4 0 4 8 12

How It Works

  • The function starts with current = n and flag = 1 (subtract mode)
  • It prints the current number and checks if it's zero or negative
  • When current <= 0, the flag changes to 0 (addition mode)
  • The recursion stops when we return to the original number N while in addition mode

Conclusion

Using recursion, we can generate the required number series without loops. The flag variable controls the direction of the series, making the solution elegant and efficient.

Updated on: 2026-03-15T12:52:36+05:30

705 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements