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 that is to be printed will start from n and will be subtracted by k till it becomes zero or negative. After that, we will start to add k to it till it becomes n again. If this process we cannot use any type of loop.

Let’s take an example to understand the problem,

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 will create a recursive function that will call itself again and keep a check on the value of the number to ensure which operation out of addition or subtraction is to be one on the number.

The function will use a flag that will help us to keep track of whether the value is to be subtracted or added.

C program to print number series without using any loop

// C program to print number series without using any loop

Example

 Live Demo

#include <iostream>
using namespace std;
void PrintSeriesRec(int current, int N, int K, bool flag){
   cout<<current<<"\t";
   if (current <= 0)
      flag = !flag;
   if (current == N && !flag)
      return;
   if (flag == true)
      PrintSeriesRec(current - K, N, K, flag);
   else if (!flag)
      PrintSeriesRec(current + K, N, K, flag);
}
int main(){
   int N = 12, K = 4;
   cout<<"The series is : 
";    PrintSeriesRec(N, N, K, true);    return 0; }

Output

The series is −

12 8 4 0 4 8 12

Updated on: 18-Jul-2020

378 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements