Learn about Sum of Digits in C using the while loop in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Sum of Digits in C using the while loop
Program:
#include<stdio.h>
int main()
{
int number,lastDigit,sum=0;
printf("Enter any number: ");
scanf("%d",&number);
while(number!=0)
{
lastDigit=number%10;
sum += lastDigit;
number/=10;
}
printf("Sum of digits = %d\n",sum);
return 0;
}
Output:
Enter any number: 121
Sum of digits = 4
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
Count the Number of Digits in an Integer using Recursion in C
C Program to Count the Number of Digits in an Integer without using a loop