Print Numbers from 1 to N without using loop

Objective: Given a number N, write an program to print from number 1 to N without using loop.

Example:

N = 20
Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Approach: Use Recursion

  • Make recursive to N = N-1.
  • In tail recursion, print the number

Code:


public class PrintNumbersWithOutLoop {
static void printNumbers(int number){
if(number<=0)
return;
//else make a recursive call
printNumbers(number1);
//print number in tail recursive
System.out.print(number + " ");
}
public static void main(String[] args) {
int n = 20;
printNumbers(n);
}
}

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.