You must Sign In to post a response.

Program to find the sum of digits of a given number until the sum becomes a single digit.

Program to find the sum of digits of a given number until the sum becomes a single digit. (e.g. 12345=>1+2+3+4+5=15=>1+5=6) in c#Asp.net 4.0


Comments

Author: Shine S25 Apr 2013 Member Level: Gold   Points : 4

you can call the function recursively till the sum become single char.
see the code below.


int sum = 0;
private void button1_Click(object sender, EventArgs e)
{
int res=GetSumOfDigits(12345);
}


private int GetSumOfDigits(int inputNum)
{
sum = 0;
char[] chars = inputNum.ToString().ToCharArray();

for (int i = 0; i < chars.Length; i++)
{
sum = sum + int.Parse(chars[i].ToString());

}
if (sum.ToString().Length > 1)
{
GetSumOfDigits(sum);
}

return sum;
}

Author: navas25 Apr 2013 Member Level: Silver   Points : 4

try this


static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string theNumber = Console.ReadLine();

int adder;

do
{
adder = 0;

foreach (char digit in theNumber)
{
adder += int.Parse(digit.ToString());
}

Console.WriteLine("Sum of digitis in {0} is: {1}", theNumber, adder);

if (adder < 10)
break;
else
theNumber = adder.ToString();

} while (true);

Console.WriteLine("Finished");
Console.ReadLine();
}

Author: Jivani25 Apr 2013 Member Level: Gold   Points : 3


static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string theNumber = Console.ReadLine();
int num= Convert.ToInt32(thenumber);
int rem=0;
int sum=0;
while( num != 0 )
{
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
string sum1=sum.tostring();
console.writeline(sum1);
}

Author: Shakil25 Apr 2013 Member Level: Gold   Points : 2

here is the code for C Language


void main()
{
int n,sum=10,n1;
clrscr();
printf("Enter a number :-");
scanf("%d",&n);
while(sum>=10)
{
sum=0;
while(n!=0)
{
n1=n%10;
sum=sum+n1;
n=n/10;
}
n=sum;
}
printf("Sum of digits :- %d ",sum);
}


thanks
regards

Author: divya25 Apr 2013 Member Level: Bronze   Points : 1

in asp.net only

Author: Shine S25 Apr 2013 Member Level: Gold   Points : 2

you can use the first example in asp.net. just call the function "private int GetSumOfDigits(int inputNum)" wherever required.