C# program to find sum of digits of a number

C# program to find sum of digits of a number  with multiple solutions viz using method, while loop, for loop and recursion. In another word, how to add the digits of a number?

For Example ,if given input number is 789 , then the sum of digits of a given Number is 7+8+9 =24.

Examples

Given input Number is : 789
sum of digits : 24

C# program to find sum of digits of a number

Example program -1 Sum of Digits in a given Integer using While loop.

class Program
    {
        static void Main(string[] args)
        {
            int  num=2489, temp, digit, sum = 0;
            temp = num;
            Console.WriteLine("Input Number : {0}",num);
            while (num > 0)
            {
                digit = num % 10;
                sum = sum + digit;
                num /= 10;
            }

            Console.WriteLine("Sum of the digits of Input Number is {0}", sum);
        }
    }

Output
Input Number : 2489
Sum of the digits of Input Number is 23

Example program -2 Sum of Digits in a given Integer using for loop in single line.

class Program
    {
        static void Main(string[] args)
        {
            int  num=2489, temp, digit, sum = 0;
            temp = num;
            Console.WriteLine("Input Number : {0}",num);
            for (sum = 0; num > 0; sum += num % 10, num /= 10) ; 

            Console.WriteLine("Sum of the digits of Input Number is {0}", sum);
        }
    }

Output
Input Number : 2489
Sum of the digits of Input Number is 23

Example program -3 Sum of Digits in a given Integer using recursive function with ternary operator.

class Program
    {
        static void Main(string[] args)
        {
            int  num=2489,sum;         
            Console.WriteLine("Input Number : {0}",num);
            Program p=new Program();
            sum = p.sumDigits(num);
            Console.WriteLine("Sum of the digits of Input Number is {0}", sum);
        }
        int sumDigits(int no)
        {
            return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
        } 
    }

Output
Input Number : 2489
Sum of the digits of Input Number is 23

Example 4-Sum of Digits in a given Integer using function.

class Program
    {
        public int sum;
        static void Main(string[] args)
        {
            int  num=2489,sum;         
            Console.WriteLine("Input Number : {0}",num);
            Program p=new Program();
            sum = p.sumDigits(num);
            Console.WriteLine("Sum of the digits of Input Number is {0}", sum);
        }
        int sumDigits(int n)
        {
            if (n == 0)
            {
                return 0;
            }

            sum = n % 10 + sumDigits(n / 10);

            return sum;
        } 
    }

Output
Input Number : 2489
Sum of the digits of Input Number is 23

Related Posts