Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with C++ Loops Exercise

Tags:

c++

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

like image 778
Alex Avatar asked Apr 13 '11 21:04

Alex


People also ask

Where can I practice C problems?

CodeChef discussion forum allows programmers to discuss solutions and problems regarding C Programming Tutorials and other programming issues.


3 Answers

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

like image 58
Benjamin Lindley Avatar answered Sep 30 '22 16:09

Benjamin Lindley


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;
like image 42
JaredPar Avatar answered Sep 30 '22 15:09

JaredPar


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.

like image 42
cHao Avatar answered Sep 30 '22 15:09

cHao