program for the sum of n numbers using recursion in java
Code:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
System.out.println(sum(n));
}
public static int sum(int n){
if(n==0){
return 0;
}
return n + sum(n-1);
}
}
i/p: 5
o/p: 15
i/p: 10
o/p: 55
Comments
Post a Comment