Add the digits of the number using C beginner level

 

Hey guys once again welcome to the Decoders blog, I hope you all are doing well and today I'm present with another logic but this time with something different it is a C logic which will help us to  get the sum of the digits of a given number using C very beginner's level.

Here is a quick sneak peak of the code which I used to get the desired output.

#include<stdio.h>

int sum(int x)
{
    int i,sum=0;
    while (x>0)
    {
        i=x%10;  //Returns the last digit of the number
        sum += i;  //Adds that digit to the sum of the previous digits and stores the
value in sum
        x=x/10;     //Remove that digit from the number and brings in the next number
    }
    return(sum);       //Returns the final sum value of the number
}
int main()
{
    int n,ans;
    printf("Enter the value of n:");
    scanf("%d",&n);
    ans=sum(n);
    printf("The sum of the given number is %d",ans);
    return(0);

}

Comments

Popular Posts