Search Tutorials

Tuesday, 23 April 2013

Java code to find sum of natural numbers upto a given number using recursion

Java program to find the sum of natural numbers upto a given number using recursion.

import java.io.*;
class SumOfNaturalNumbers
{
 public static void main(String args[]) throws IOException
 {
 BufferedReader br = new BufferedReader(new
 InputStreamReader(System.in));
 SumOfNaturalNumbers call = new SumOfNaturalNumbers();
 System.out.print("Enter a number : ");
 int n = Integer.parseInt(br.readLine());
 System.out.println("\nSum of Natural Numbers till " +n +" = "+call.sum(n));
 }
 int sum(int n)
 {
  if(n==1)
  return 1;
 else
  return n+sum(n-1);
 }
}

ALGORITHM:-

1. Start

2. Accept a number n from user.

3. Using method of recursion, add all the numbers upto n.

4. Print the sum.

5. End

OUTPUT:-

Java code to find sum of natural numbers upto a given number using recursion

Enter a number : 25

Sum of Natural Numbers till 25 = 325

Related Programs:-

Calculate the Power of a number using recursion

Print the Initials of a name

Find the frequency of each character in a string

Arrange the letters of a word in alphabetical order

Find the pig Latin equivalent of a word

No comments:

Post a Comment

Back to Top