Java Program for Print Number series without using any loop
Givens Two number N and b, 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 becomes the original number(N).
Remember: Here we are 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
Output explanation: We can do it using recursion idea 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 functions we used a Boolean flag.
JAVA
import java.io.*;
import java.util.*;
class GFG {
public static void PrintNumber( int N, int Original,
int K, boolean flag)
{
System.out.print(N + " ");
if (N& lt; = 0 )
flag = !flag;
if (N == Original & amp; & !flag)
return ;
if (flag == true ) {
PrintNumber(N - K, Original, K, flag);
return ;
}
if (!flag) {
PrintNumber(N + K, Original, K, flag);
return ;
}
}
public static void main(String[] args)
{
int N = 20 , K = 6 ;
PrintNumber(N, N, K, true );
}
}
|
Output:
20 14 8 2 -4 2 8 14 20
Time complexity: O(N) for given input N
Auxiliary space: O(1)
Please refer complete article on Print Number series without using any loop for more details!
Last Updated :
04 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...