Recursive sum to find single digit - without recursive function

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 1168
I have a number as N=2345

If I sum them the result will be 2+3+4+5 =14;

If I further sum them it will be 1+4 = 5; which is a single digit;

How to do this without recursive function?

int N = 2345;

while (N >= 10)
N = N.ToString()
.Sum(x => int.Parse(x.ToString()));

Comments or Responses

Posted by: Saranpselvam on: 5/12/2014 Level:Starter | Status: [Member] | Points: 10
Hi Suppose if we should not convert that integer to any other format then we can use like this

class Program
{
static void Main(string[] args)
{
int val = 1245;

Program a = new Program();
int result = a.sum(val);
Console.WriteLine("result="+result);
Console.ReadLine();

}

public int sum(int num)
{

if (num != 0)
{

return (num % 10 + sum(num / 10));
}
else
{
return 0;
}
}
}

Login to post response