C program to sum digits of a number

This post explain how to calculate sum of digits of a 4 digit number without looping.

/* Program to sum digits of number*/
#include<stdio.h>
int main()
{
int num,last_digit,sum=0;
printf(“Enter a 4 digit number\n”);
scanf(“%d”,&num);
last_digit=num%10;
num=num/10;
sum=sum+last_digit;
last_digit=num%10;
num=num/10;
sum=sum+last_digit;
last_digit=num%10;
num=num/10;
sum=sum+last_digit;
sum=sum+num;
printf(“the sum of 4 digit number is %d\n”,sum);
return 0;
}

Output:

Enter a 4 digit number
2345
the sum of 4 digit number is 14

Leave a Reply

Your email address will not be published. Required fields are marked *