w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Function : To calculate the sum of the individual digits of a number

C# Sharp Function: Exercise-10 with Solution

Write a program in C# Sharp to create a function to calculate the sum of the individual digits of a given number.

Pictorial Presentation:

C# Sharp Exercises: Function : To calculate the sum of the individual digits of a number

Sample Solution:

C# Sharp Code:

using System;
public class funcexer10
{     
public static int SumCal( int n ) 
    { 
       string n1 = Convert.ToString(n);
       int sum = 0;  
       for (int i = 0; i < n1.Length; i++)
         sum += Convert.ToInt32(n1.Substring(i,1));
         return sum;
    }
 
public static void Main() 
    {
	  int num;
	  Console.Write("\n\nFunction : To calculate the sum of the individual digits of a number :\n");
      Console.Write("--------------------------------------------------------------------------\n");   
      Console.Write("Enter a number: ");
      num = Convert.ToInt32( Console.ReadLine() );
      Console.WriteLine("The sum of the digits of the number {0} is : {1} \n",num,SumCal(num));    
    }
}

Sample Output:

Function : To calculate the sum of the individual digits of a number :                                        
--------------------------------------------------------------------------                                    
Enter a number: 25                                                                                            
The sum of the digits of the number 25 is : 7 

Flowchart :

Flowchart: C# Sharp Exercises - Function : To calculate the sum of the individual digits of a number

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to create a function to check whether a number is prime or not.
Next: Write a program in C# Sharp to create a recursive function to find the factorial of a given number.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming