In this program, we take input from the user and find the sum of digits in c using for loop and while loop. for example, the sum of digits of 123 is 1+2+3=6
take the number from the user, divide the number into individual digits, and adding those individuals (Sum) digits using for Loop
#include<stdio.h>
int main()
{
int sum=0,n,r,i;
printf("\n enter the number:");
scanf("%d",&n);
for(i=n;i>0;i=i/10)
{
r=i%10;
sum+=r;
}
printf("\n sum of digit=%d",sum);
return 0;
}
Reduce the number of line of code by writing for loop in these ways
for(i=n;i>0;sum+=i%10,i=i/10) {
}
enter the number:123 sum of digit=6
take the number from the user, divide the number into individual digits, and adding those individuals digits using for Loop
#include<stdio.h>
int main()
{
int r,n,sum=0;
printf("enter the number:");
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("\n sum of digit=%d",sum);
return 0;
}
enter the number:156 sum of digit=12
n
.r=n%10
.sum
.