This is a Java Program to print First N Natural Numbers using Recursion.
Enter any number as an input. Now we make a new method named natural which calls itself until we get the desird result.
Here is the source code of the Java Program to print First N Natural Numbers using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Natural
{
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter any number:");
n = s.nextInt();
Natural obj = new Natural();
System.out.print("Natural numbers till "+n+" :");
obj.natural(n,1);
}
int natural(int y, int i)
{
if(i <= y)
{
System.out.print(i+" ");
return(natural(y,++i));
}
return 1;
}
}
Output:
$ javac Natural.java $ java Natural Enter any number:8 Natural numbers till 8 :1 2 3 4 5 6 7 8
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice Programming MCQs
- Practice BCA MCQs
- Check Programming Books
- Check Java Books
- Apply for Java Internship