C# program to calculate the sum of all digits of a number using recursion

Here, we are going to learn how to calculate the sum of all digits of a number using recursion in C#?
Submitted by Nidhi, on September 03, 2020

Here we will input an integer number and then calculate the sum of all digits using the recursive method.

Program:

The source code to calculate the sum of all digits of a number using recursion is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to calculate the sum of all digits 
//of a number using recursion

using System;

class Sample
{
    public static int SumOfDigit(int number)
    {
        if (number == 0)
        {
            return 0;
        }
        else
        {
            int rem = 0;

            rem = number % 10;
            return (rem + sumOfDigit(number / 10));
        }
    }

    public static void Main()
    {
        int num = 0;
        int sum = 0;

        Console.Write("Enter the number: ");
        num = int.Parse(Console.ReadLine());

        sum=SumOfDigit(num);

        Console.WriteLine("Sum of digits: " + sum);
    }
}

Output:

Enter the number: 342
Sum of digits: 9
Press any key to continue . . .

Explanation:

In the above program, we created a Sample class that contains two static methods SumOfDigits() and Main() method. In the Main() method, we declared an integer variable num and read the value of variable num, and then find the sum of all digits of the input number and print on the console screen.

Here, the method SumOfDigits() is a recursive method. Here we find the last digit of the number in every recursive call by finding the remainder, and then divide the number by 10 in every recursive call till the number is greater than 0.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.