//program to get sum of all digits present in a number.
#include<stdio.h>
#include<conio.h>
#include<conio.h>
void main()
{
int n,rem,sum=0;
printf("enter a number for 'n'\n");
scanf("%d",&n);
{
int n,rem,sum=0;
printf("enter a number for 'n'\n");
scanf("%d",&n);
while(n!=0)
{
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("the sum=%d",sum);
getch();
}
--------------------------------------------------------------------------------------------------------
logics in mind:-
>first we enter a number(for 'n').
->to get sum of digits,first we have to get all digits one by one.If we have number 123 then its sum is 3+2+1=6. It means, first we have to get 3 then 2 and then 1.
->For this,
->we have to divide by 10 to get last digit.
->Then we go for sum using sum=sum+digit.
-> to get second digit, we get first 12 and for this , we use 123/10.It is done to get integer part only.
->We repeat this until the value reaches 0 and last sum is received. We use loop for this as shown above in the code.
->then final sum is displayed.
No comments:
Post a Comment