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; }
//Here 12356 is the integer parameter for which we will get the sum of alternative digits int n = sumDigits(12356);
Thanks, A2H My Blog
Login to post response