Become Our Fan on Social Sites!

Facebook Twitter

Google+ RSS YouTube

Thursday, 26 September 2013

C Program To Find Out Sum Of Digits Of Given Number

Sum of digits : If you enter number like 234 then output is 9 (2+3+4). That is sum of all digits of entered number. Following C program find out sum of digits of given number.




1) Sum of digits using while loop

#include<stdio.h>

void main()
{
    int no, r, sum = 0;

    printf("Enter No. : ");
    scanf("%d",&no);

    while(no != 0)
    {
        r = no % 10;
        sum = sum + r;
        no = no / 10;
    }

    printf("Sum Of Digits = %d",sum);
}


2) Sum of digits using Recursion

#include<stdio.h>

int sume_of_digits(int);

void main()
{
    int no, result;

    printf("Enter No.: ");
    scanf("%d", &no);

    result = sume_of_digits(no);

    printf("Sum of digits = %d", result);
}
int sume_of_digits(int no)
{
    static int sum = 0; // because it happens only once

    if (no == 0)
          return 0;

    sum = no % 10 + sume_of_digits( no / 10 );

    return sum;
}

0 comments :

Post a Comment