Number program - Find sum of odd digits

Page 1 of 1

1 Replies - 7907 Views - Last Post: 14 November 2009 - 10:35 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=138984&amp;s=571afba401579d38a44d8219be1cea14&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 makan007

Reputation: 0
• Posts: 16
• Joined: 31-October 09

Number program - Find sum of odd digits

Posted 14 November 2009 - 05:49 AM

What should be the correct way to find the sum of odd digit for Line 21?
For example, 123456
sumEvenDigits = 2 + 4 + 6 = 12

```#include <iostream>
using namespace std;

int main ()
{
int n;
int numDigits = 0, numEvens = 0;
int numOdds = 0, sumDigits = 0;
int sumEvenDigits;

cout << "Enter a positive number: ";
cin >> n;

while (n > 0)
{
aDigit = n % 10;   // Get the last digit

numDigits++;
//	  sumEvenDigits = numEvens++;

++numOdds;
else
++numEvens;

n /= 10;

}

cout << "The no of digits is " << numDigits << endl;
cout << "The no of odd digits is " << numOdds << endl;
cout << "The no of even digts is " << numEvens << endl;
cout << "The sum of all digits is " << sumDigits << endl;
cout << "The sum of even digits is " << sumEvenDigits << endl;
return 0;
}

```

Is This A Good Question/Topic? 0

Replies To: Number program - Find sum of odd digits

#2 gronk

Reputation: 13
• Posts: 168
• Joined: 28-October 09

Re: Number program - Find sum of odd digits

Posted 14 November 2009 - 10:35 AM

If you're going to proceed by popping the last digit off the number each time round the loop until it is zero, then you're not going to know the length of the number, and consequently whether any digit is an even or odd digit, until the end of the loop. So you're going to have to maintain two sums, then pick the one that corresponds to whether the length is even or odd. So 123456->2+4+6=12, but 23456->3+5=8.

aDigit is the last digit on the number, so you would just add that to whichever total is relevant to each pass around the loop.