You must Sign In to post a response.
  • Category: ASP.NET

    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
  • #713764
    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;
    }

    Regards,
    Shine

  • #713766
    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();
    }

  • #713768
    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);
    }

    I Hope To Use Full..
    And Choice The Best Answers

    php-wordpress Developer
    you can any problem to php wordpress to contact me
    jivanibhai7306@gmail.com
    Thanks!!...

  • #713771
    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

    Regards,
    Shakil Sama

  • #713774
    in asp.net only

  • #713779
    you can use the first example in asp.net. just call the function "private int GetSumOfDigits(int inputNum)" wherever required.
    Regards,
    Shine


This thread is locked for new responses. Please post your comments and questions as a separate thread.
If required, refer to the URL of this page in your new post.