Write a C program to find sum of digits? [Easy Code]

I think you understand the program. If NO… don’t worry I am explaining you all – Today, we are writing a C program to find sum of digits using a loop.

C program to find sum of digits

#include<stdio.h>
#include<conio.h>

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

printf("Enter any number");
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum= sum + r;
n=n/10;
}

printf("Sum of digits of number=%d",sum);
getch();
}

Output

Enter any number 1253
Sum of digits of number=11

Program Code Execution (PCE)

I already explained in my previous articles like Armstrong Number, Palindrome Number about finding a digit from a number. Similarly, in the above program code, I find a digit from number (n) using a modulus operator.

Then after getting each digit from a number, I took a new variable ‘sum’ and add these digits into the ‘sum’ variable.

Finally, I print the value of the ‘sum’.

So you learn how to write a C program to find sum of digits?

Please ask your queries in below comment section. If you love travelling you can read our travelling blog.

Leave a Comment

error: Don\'t make piracy - Write your own content :)