1 Replies - 4252 Views - Last Post: 14 November 2009 - 10:35 AM Rate Topic: -----

#1 makan007  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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 aDigit;
	int sumEvenDigits;
	
	cout << "Enter a positive number: ";
	cin >> n;
	
	while (n > 0)
	{ 
		aDigit = n % 10;   // Get the last digit
	
		numDigits++;
		sumDigits += aDigit;	
	//	  sumEvenDigits = numEvens++;
		
		if (aDigit % 2)
			++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  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1