Find the sum of n natural numbers using recursion

Problem statement:- Program to Find the sum of n natural numbers using recursion.

Data requirement:-

   Input Data:- n

  Output Data:-SumOfNaturalNumber(n)

Program in C

Here is the source code of the C Program to Find the sum of n natural numbers using recursion.

Code:

#include<stdio.h>
int SumOfNaturalNumber(int n)
{
   if(n>0)
   return SumOfNaturalNumber(n-1)+n;
}
int main()
{
    int n;
    printf("Enter the N Value:");
    scanf("%d",&n);
    printf("Sum Of N Natural Number Using Recursion is:%d",SumOfNaturalNumber(n));
}

Input/Output:
Enter the N Value:10
Sum Of N Natural Number Using Recursion is:55

Program in C++

Here is the source code of the C++ Program to Find the sum of n natural numbers using recursion.

Code:

#include<iostream>
using namespace std;
int SumOfNaturalNumber(int n)
{
   if(n>0)
   return SumOfNaturalNumber(n-1)+n;
}
int main()
{
    int n;
    cout<<"Enter the Number:";
    cin>>n;
    cout<<"Sum Of N Natural Number Using Recursion is:"<<SumOfNaturalNumber(n);
}

Input/Output:
Enter the Number:5
Sum Of N Natural Number Using Recursion is:15

Program in Java

Here is the source code of the Java Program to Find the sum of n natural numbers using recursion.

Code:

import java.util.Scanner;
public class SumOfNNaturalNumber {
static int SumOfNaturalNumber(int n)
    {
   if(n>0)
return n+SumOfNaturalNumber(n-1);
   else
   return n;

}
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
System.out.print("Enter the N Value:");
int n=cs.nextInt();
System.out.print("Sum Of N Natural Number Using Recursion is:"+SumOfNaturalNumber(n));
cs.close();
}
}

Input/Output:
Enter the N Value:15
Sum Of N Natural Number Using Recursion is:120

Program in Python

Here is the source code of the Python Program to Find the sum of n natural numbers using recursion.

Code:

def SumOfNaturalNumber(n):
    if n>0:
        return n+SumOfNaturalNumber(n-1)
    else:
        return n
n=int(input("Enter the N Number:"))
print("Sum of N Natural Number Using Recursion is:",SumOfNaturalNumber(n))

Input/Output:

Post a Comment

0 Comments