Sum of digits of a Number in C

In this tutorial we are going to learn about adding digits present in a given number.The main concept of this problem is…..If the input is 225 then the output should be 9 i.e is addition 2+2+5.The logic behind it is we need to get the single digits of the number..i.e is 5,2,2 separately.

To exclude the numbers from the given digit we use the number 10.The special property of number 10 is, if a number is divided by 10 then the remainder will be the last digit of the number and quotient will be other digits present in the number.For example let the number be 225.If we divide the number by 10 then the remainder will be 5 and the quotient will be 22.Therefore we got the number 5 from the given digit.Now the program is

#include<stdio.h>
#include<conio.h>
void main()
{
	int num,remainder,sum=0;
	clrscr();
	printf("\t************Sum of digits of given number**********");
	printf("\n\nEnter any number to find the sum of digits present:");
	scanf("%d",&num);
	while(num>0)
	{
		remainder = num%10;
		num = num/10;
		sum = sum +remainder;
	}
	printf("\nSum of digits of given number is:%d",sum);
	getch();
}

Output:
sumofdigits
Download source code

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C and tagged , , , , , , . Bookmark the permalink.

1 Response to Sum of digits of a Number in C

  1. Pingback: Palindrome Number Program in C | letusprogram...!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s