// program to illustrate recursion
/* Sum of N natural numbers
limit of N numbers entered by the user.
int sum=0;
for(i=1;i<=n;i++)
sum = sum+i;
cout<<sum;
*/
import java.io.*;
public class Recursion
{
public static int Sum(int n)
{
if(n==1)
return 1;
return n+Sum(n-1);
}
public static void main(String[] args) throws Exception
{
int n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the limit of the natural no : ");
n=Integer.parseInt(br.readLine());
int total=Sum(n);
System.out.println("Sum is : "+total);
}
}
Output
Enter the limit of the natural no :
10
Sum is : 55
/* Sum of N natural numbers
limit of N numbers entered by the user.
int sum=0;
for(i=1;i<=n;i++)
sum = sum+i;
cout<<sum;
*/
import java.io.*;
public class Recursion
{
public static int Sum(int n)
{
if(n==1)
return 1;
return n+Sum(n-1);
}
public static void main(String[] args) throws Exception
{
int n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the limit of the natural no : ");
n=Integer.parseInt(br.readLine());
int total=Sum(n);
System.out.println("Sum is : "+total);
}
}
Output
Enter the limit of the natural no :
10
Sum is : 55
No comments:
Post a Comment