Alex
Alex

Reputation: 3181

Need help with C++ Loops Exercise

From Cay Horstmann's "C++ For Everyone" Chapter 4: Loops

Write a program that adds up the sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17)

I don't know how to make the computer "see" the numbers like separate them

Upvotes: 5

Views: 538

Answers (4)

Pirooz
Pirooz

Reputation: 1278

People here rather not provide you with the answer to your exercise, but to provide you with hints so that you can find the answer on your own and more importantly understand it.

To start, the following arithmetic operations will help you:

loop:
  right_most_digit = n % 10
  n = n / 10
end_loop

Upvotes: 0

cHao
cHao

Reputation: 86506

The last digit of a base-10 integer i is equal to i % 10. (For reference, % is the modulus operator; it basically returns the remainder from dividing the left number by the right.)

So, now you have the last digit. Once you do, add it to a running total you're keeping, divide i by 10 (effectively shifting the digits down by one place), or in your case 100 (two places), and start back at the beginning. Repeat until i == 0.

Upvotes: 3

JaredPar
JaredPar

Reputation: 754595

Here's a hint. C++ has the modulus operator %. It will produce the remainder when two numbers are divided together. So if I wanted to know the last digit in a number which was greater than 10 I would modulus 10 and get the result

int lastDigit = number % 10;

Upvotes: 3

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

n % 10 gets the value of the one's digit. You can figure it out from there right?

Upvotes: 8

Related Questions