Friday 28 August 2015

Sum of first N natural numbers by recursion in Java

Dear Friends,

I am here with you with another simple problem.

If we have a natural number, N then we need to find the sum of first N natural numbers.

This has a simple solution which can be simply printing the value of N*(N+1)/2. For learning purpose lets try this problem using recursion. Friends please find below the code using recursion.


package com.recursion.sum.numbers;

import java.util.Scanner;

/**
 * This can be solved using simple formula for sum of first n natural numbers
 * but for learning purpose we are solving it using Recursion
 * 
 * @author krishna.k
 *
 */
public class SumOfFirstNNumbers {
    public static void main(String[] args) {
        System.out.println("Enter the Number");
        Scanner sc = new Scanner(System.in);
        int number = sc.nextInt();
        System.out.println("Sum of first "+ number+" numbers is "+computeSum(number));
    }

    public static int computeSum(int number) {
        if(number == 1){
            return 1;
        }
        return number + computeSum(number-1);
    }
}

No comments:

Post a Comment

Hi Friends, Please leave your comments as they shall be greatest motivation , shall help me make corrections to my existing posts and will enable me to create better posts. :)