Print Number series without using any loop
Problem – Givens Two number N and K, our task is to subtract a number K from N until number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that number become the original number(N).
Note : Not allow to use any loop.
Examples :
Input : N = 15 K = 5 Output : 15 10 5 0 1 5 10 15 Input : N = 20 K = 6 Output : 20 14 8 2 4 2 8 14 20
Explanation – We can do it using recursion idea is that we call the function again and again until N is greater than zero (in every function call we subtract N by K). Once the number becomes negative or zero we start adding K in every function call until the number becomes the original number. Here we use a single function for both addition and subtraction but to switch between addition or subtraction function we used a Boolean flag.
Code –

// C++ program to Print Number
// series without using loop
#include <iostream>
using
namespace
std;
// function print series
// using recursion
void
PrintNumber(
int
N,
int
Original,
int
K,
bool
flag)
{
// print the number
cout << N <<
" "
;
// change flag if number
// become negative
if
(N <= 0)
flag = !flag;
// base condition for
// second_case (Adding K)
if
(N == Original && !flag)
return
;
// if flag is true
// we subtract value until
// number is greater then zero
if
(flag ==
true
) {
PrintNumber(N  K, Original, K, flag);
return
;
}
// second case (Addition )
if
(!flag) {
PrintNumber(N + K, Original, K, flag);
return
;
}
}
// driver program
int
main()
{
int
N = 20, K = 6;
PrintNumber(N, N, K,
true
);
return
0;
}
Output :
20 14 8 2 4 2 8 14 20
Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/printnumberserieswithoutusingloop/
We have built the accelerating growthoriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide