## Jun 1, 2010

### PPP: The Sum of Digits

A Programing Practice Problem where the user provides a positive integer to receive back the total of the digits in the given number.

### Sum of Digits

Provide me with an application that takes an input int and returns an int that is the total of each digit of that number. In the case of 1024, it should return 7, as 1 + 0 + 2 + 4 = 7. Be sure that anything from a single digit number to an 8 digit or higher number still runs correctly.

### Single Digit Sum of Digits

Taken to the next step, repeat the process over and over until the return value is a single digit number.

### Extra Credit: Crazy Mode

Allow the user to change the app away from base 10, such as base 2 or base 16. This is called crazy for a reason.

J. Ash said...

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace SumOfInput
{
public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

lblTitle.Text = "Welcome to The Sum of Digits";
lblInstructions.Text = "Input an integer of any length and press 'Get Sum!' to find the sum of all digits entered.";
lblResult.Text = "";
}

protected void btnGetSum_Click(object sender, EventArgs e)
{
int iDigit, iCount, iLen;
string sub, input, result;

input = txtInput.Text;

iLen = input.Length;
iDigit = 1;

int[] digits;
digits = new int[iLen];

for (iCount = 0; iCount < iLen; iCount++)
{
sub = input.Substring(iCount, iDigit);
digits[iCount] = int.Parse(sub);
}

result = digits.Sum().ToString();

lblResult.Text = "The sum of your digits is " + result;
}

protected void btnClear_Click(object sender, EventArgs e)
{
txtInput.Text = "";
lblResult.Text = "";
}
}
}

J. Ash said...

By the way, I did not program any validation checking for input.