Java Program to Print All Natural Numbers Using Recursion

First N natural numbers

Java program to print all the natural numbers from 1 to N using recursion has been shown here.






1. Java Program & output to Print First N Natural Numbers using recursion

Code has been copied
/************************************************
                alphabetacoder.com
 Java program to print all natual numbers from 1 
 to n  using recursion
*************************************************/

import java.util.Scanner;
public class NaturalNumber {
    public static void main(String args[]) {
        //System.in is a standard input stream
        // sc is the object
        Scanner sc = new Scanner(System.in);
        int n;

        //take input of the number upto 
        // which numbers will be printed
        System.out.print("Enter the upper limit=");
        n = sc.nextInt();

        System.out.print("First " + n + " natural numbers are : ");
        // call the recursive function to print
        // the natural numbers
        printUptoN(n);
    }
    // recursive function
    public static void printUptoN(int n) {
        //condition for calling
        if (n > 1)
            printUptoN(n - 1);
        System.out.print(" " + n);
    }
}

Output


Case 1:

Enter the upper limit=7

First 7 natural numbers are : 1 2 3 4 5 6 7


Case 2:

Enter the upper limit=6

First 6 natural numbers are : 1 2 3 4 5 6