Write a function that takes an integer as a parameter and adds the alternate digits in the integer

Posted by Bhanu6545 under C# on 3/20/2014 | Points: 10 | Views : 512 | Status : [Member] | Replies : 1
Write a function that takes an integer as a parameter and adds the alternate digits in the integer




Responses

Posted by: A2H on: 3/20/2014 [Member] [MVP] Silver | Points: 25

Up
0
Down
Hi,
You can achieve your requirement with the below implementation

 public  int sumDigits(int inputValue)

{
//Varibale to hold the sum
int TotalSum = 0;
//Convert your integer to array of digits
int[] aryDigits = Array.ConvertAll(inputValue.ToString().ToArray(), x => (int)x - 48);
//Loop through the array take the alternative numbers
for (int i = 0; i < aryDigits.Length; i = i + 2)
{
//Add the alternative numbers and then assign it to variable
TotalSum = TotalSum + Convert.ToInt32(aryDigits[i]);

}
//Return the total value
return TotalSum;
}


You call the above method like given below

//Here 12356 is the integer parameter for which we will get the sum of alternative digits
int n = sumDigits(12356);


You can find a working sample demo in below link
http://dotnetfiddle.net/AYCRZF

Please Mark my Reply as Answer if it answers your question

Thanks,
A2H
My Blog

Bhanu6545, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response