Answer to Question #284558 in Algorithms for Daemus

Question #284558

(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. 



1
Expert's answer
2022-01-03T10:46:31-0500

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)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS