Java Program to calculate Sum of 1 to N Numbers using Recursion

/* Sum of 1 to N natural numbers can be calculated using for / while loop very easily. In the below java program we have calculated sum of 1 to N numbers using recursive function without using any loop. In Recursive, the function calls itself until some condition is met. In our example, sumR(int num) is called until num becomes 1 .

The following code calculates Sum 1 to N numbers */


package com.javaonline;

import java.io.*;

// This program computes sum 1 to N numbers using recursion

public class SumRecursion
{

public static void main(String[] args)
{
System.out.println("Enter N");

try
{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
int number= Integer.parseInt(br.readLine()); // reads number as a string from keyboard and converts to number

/* Scanner sc = new Scanner(System.in); // We can also use this lines for getting N
int number = sc.nextInt(); */

int sum = sumR(number); // calling sumR function

System.out.println("Sum of " + number + " Numbers using Recursion is : " + sum);

}

catch (Exception e)
{
System.out.println ("Give Proper Input i.e. Enter Numeric value only and with in range");
}
}

// Computes a Sum of N numbers by recursion.

public static int sumR(int num)
{
int sum;
if(num==1) return(1) ;

else sum=num + sumR(num-1); // function calls itself
return sum;

}

}

 

You may also like

Leave a Reply

Be the First to Comment!