Exercise
Function Sumdigits
Objective
Write a C# function SumDigits that receives a number and returns any results in the sum of its digits. For example, if the number is 123, the sum would be 6.
Console.Write( SumDigits(123) );
6
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Main method where the program starts
public static void Main()
{
// Calling the SumDigits function with the number 123 and printing the result
Console.WriteLine(SumDigits(123)); // The sum of digits of 123 is 6, which will be printed
}
// Function to calculate the sum of digits of a given number
public static int SumDigits(int number)
{
// Variable to store the sum of the digits
int sum = 0;
// While loop to iterate through each digit of the number
while (number > 0)
{
// Add the last digit of the number to sum
sum += number % 10; // The modulus operation gets the last digit of the number
number /= 10; // Removing the last digit by dividing the number by 10
}
// Returning the sum of digits
return sum; // The result is the sum of all digits
}
}