(Sum the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
Program on C:
#include <stdio.h>
int main() {
int x, digit, sum;
scanf("%d", &x);
sum = 0;
while (x>0) {
digit = x%10;
x = x / 10;
sum += digit;
}
printf("The sum of digits is %d\n", sum);
return 0;
}
Program on Python:
x = int(input())
s = 0
while x > 0:
s = s + x%10
x = x // 10
print('The sum of all digits is', s)
Comments
Leave a comment