Write a C program to find the sum of digits in a given number.
int main() {
int n, rem, sum = 0;
/* get the input from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of digits in the given input */
while (n > 0) {
rem = n % 10;
sum = sum + rem;
n = n / 10;
}
/* print the result */
printf("Sum of digits:%d\n", sum);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the value for n:123456789
Sum of digits:45
Enter the value for n:123456789
Sum of digits:45
No comments:
Post a Comment