c-sharp
  1. c-sharp-program-to-find-the-sum-of-natural-numbers-using-recursion

Program to Find the Sum of Natural Numbers using Recursion - (C# Basic Programs)

Finding the sum of natural numbers using recursion is a common programming problem that helps improve problem-solving skills. In this tutorial, we will discuss a program to find the sum of natural numbers using recursion in C# programming language.

Syntax

The syntax for finding the sum of natural numbers using recursion in C# is as follows:

public int Sum(int num)
{
    if (num == 0)
    {
        return 0;
    }
    else
    {
        return num + Sum(num - 1);
    }
}

Example

using System;

namespace SumNaturalNumbersRecursion
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, sum;
            Console.WriteLine("Enter a number: ");
            num = int.Parse(Console.ReadLine());
            sum = Sum(num);
            Console.WriteLine("Sum of natural numbers from 1 to {0} is {1}", num, sum);
        }

        static int Sum(int num)
        {
            if (num == 0)
            {
                return 0;
            }
            else
            {
                return num + Sum(num - 1);
            }
        }
    }
}

Output:

Enter a number:
5
Sum of natural numbers from 1 to 5 is 15

Explanation

The program uses a recursive function called Sum to calculate the sum of natural numbers.

  • If the input num is 0, the function returns 0 (base case).
  • If the input num is not 0, the function recursively calls itself with num-1 and adds num to the result.

Use

This program helps developers understand how recursion works and how to use recursion to solve problems. It can be used as a starting point for more complex programming problems that involve recursion.

Summary

In this tutorial, we have discussed a program to find the sum of natural numbers using recursion in C# programming language. We have seen the syntax, example, explanation, and use of recursion in programming. By practicing this program, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges using recursion.

Published on: