Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding Digits of a Whole #

Status
Not open for further replies.

stathread

Programmer
Jan 17, 2006
38
US
pretty easy I would think, I will most likely figure it out after I ask but I will ask anyways.

My number: 123456789
Id like to split it up and add the digits:1+2+3+4+5+6+7+8+9

I tried to put it in a loop and do a substring then convert it back to a number but im having problems :(

Thanks in advance.
 
Code:
string theNumber = "123456789";
			char[] numArray = theNumber.ToCharArray();
			int theTotal = 0;

			for (int i=0; i<numArray.Length; i++)
			{
				//Console.WriteLine(numArray[i].ToString());
				theTotal += Convert.ToInt32(numArray[i].ToString());
			}

			Console.WriteLine(theTotal.ToString());

There may be an easier way, but this is just what came through right off of the top of my head.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Blast! I didn't see you had already got it, oh well.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 

This is for others.


for (int i=0;i<subscriberid.Length;i++)
{
string str = new string(subscriberid.ToCharArray(i,1));
integer = Convert.ToInt32(str)+integer;
}
textBox1.Text= integer.ToString();
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top