English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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. Use the int operators / and %.

2007-02-21 15:05:26 · 5 answers · asked by camarodriver682005 2 in Computers & Internet Programming & Design

Yeah see, me and a group of like 5 friends have been pooling our resources and the truth is out professor is totally over our heads. We have been working at this problem and are completely lost. Any suggestions?

2007-02-21 15:21:43 · update #1

5 answers

Here is the main logic section.
Hint: In a loop, you take mod 10, add that to sum, then divide by 10.

Spoiler from here on down.
int x; // x is the number which you take from input
// get x from input here
int sum = 0;
while (x != 0)
{
sum += x % 10;
x /= 10;
}
// print sum here.

2007-02-21 15:49:41 · answer #1 · answered by CaptainObvious 3 · 1 0

Basically, divide by 10 in integer then multiply by 10, this puts a zero in the units place. Subtract the new number from the original, giving the digit in the tens place. Divide by 10 to move the number over and repeat until value is 0, adding as you go.

2007-02-21 15:18:26 · answer #2 · answered by Mike1942f 7 · 0 0

Why dont you get a book on beginning Java programming? Go to amazon and type "beginner Java" or something like that. Then work through the book. I'm sure there will be many examples.

2016-05-23 21:58:10 · answer #3 · answered by Anonymous · 0 0

I think this might work. Possibly. If it doesn't, I can make something better that does.

public int sumOfDigits(int num) {
int sum = 0;
while (num >= 0 && num <= 1000) {
sum += num % 10;
num /= 10;
}
return sum;
}

2007-02-21 15:51:50 · answer #4 · answered by Alex 2 · 0 0

"homework"
A school task performed by a *student* to satisfy the teacher.

Don't post homework just because you're too lazy to do it yourself. Maybe if you TRY to solve it, then run into a problem, people MIGHT want to help you. But just giving the problem is completely unforgivable.

2007-02-21 15:18:34 · answer #5 · answered by mc_barron 2 · 0 0

fedest.com, questions and answers