C# Sharp Exercises: Function : To calculate the sum of the individual digits of a specified 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:
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 :
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?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework