In this tutorial, we will write a C# program to get a number and display the sum of the digits. We will see the use of a do-while loop and get the user inputs with source code.
Explanation: The program takes a number from the user as input and passes that number to a function where the calculation is done. The do-while loop is used to iterate the number digit by digit and finally add the number and display the result at the end.
C# Program to find the Sum of Digits of a Number using function
source code: Program to calculate the sum of the digits in C#.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using System; public class SumOfDigits { public static void CalculateSum(int x) { var sum = 0; var rem = 0; do { rem = x % 10; x = x / 10; sum = sum + rem; } while (x != 0); Console.WriteLine("The sum is: " + sum); } public static void Main(string[] s) { Console.WriteLine("Enter a number to find the sum of the digits:"); var input = Console.ReadLine(); var num = int.Parse(input); CalculateSum(num); } } |
Output: