- Course
- Functions B
- Function to add the digits of a number
Function to add the digits of a number
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program that asks the user for a number and save it in a text string. You must implement a function called AddDigits that receives the text as a parameter and returns the sum of its digits.
Input
2222222222222222222222
Output
44
Solution
using System;
public class FunctionAddDigitsNumber
{
public static void Main(string[] args)
{
string number = Console.ReadLine();
Console.WriteLine(number);
}
public static int AddDigits(string number)
{
int sum = 0;
for (int i = 0; i < number.Length; i++)
{
sum += Convert.ToInt32(number.Substring(i, 1));
}
return sum;
}
}