Print numbers from 1 to N using recursion in java.
Using global variable
public class PrintOnetoN {
static int n;
public static void print(int x){
if(x>n) return;
System.out.println(x);
print(x+1);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("enter value of n=");
n=sc.nextInt();
print(1);
}
}
■》Output->
enter value of n=8
1
2
3
4
5
6
7
8
Without global variable
import java.util.Scanner;
public class PrintOnetoN {
public static void print(int n){
if(n==0) return;
print(n-1);
System.out.println(n);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("enter value of n=");
int n=sc.nextInt();
print(n);
}
}
■》Output->
enter value of n=5
1
2
3
4
5
Comments
Post a Comment