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:
Download source code
Pingback: Palindrome Number Program in C | letusprogram...!!!