C Language

May 28, 2023

How to use sum of digits of any number in C Language

Program to use sum of digits of any number in C Language


#include <stdio.h>
int main()
{
    int n, sum = 0, rem;
    printf("enter a number :");
    scanf("%d", &n);
    while (n > 0)
    {
        rem = n % 10;
        sum += rem;
        n /= 10;
    }
    printf("sum of digits=%d\n", sum);
    return 0;
}

output


enter a number
1452
sum of digits=12

by : Nadeem Khan

Quick Summary:

value of rem : 1452%10=2, value of sum : 0+2=2, value of n :1452/10=145
value of rem : 145%10=5, value of sum : 2+5=7, value of n : 145/10=14
value of rem : 14%10=4, value of sum : 7+4=11, value of n : 14/10=1
value of rem :1%10=1, value of sum : 11+1=12, value of n : 1/10=0
sum of digits=12