Enter integers and print with its even number summed.

Hi I'm doing lab HW and am so struggling with this. The hw is about asking users to type integers and the output returns the numbers with its
even digits summed. Odd numbers should be omitting.
So for example, if a user enter 3456 then the output should be 4+6 = 10.
I don't know what I should put in the while loop as well as if statement within the returning function. Help me!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

int addEvenDigits(int num);

int main()
{
	int num = 0, sumEven;
	cout << "Please enter integers. Then, it will output with its even digits summed. " << endl;
	while (num % 2 == 0)
	{
		cin >> num;
		sumEven = addEvenDigits(num);
		cout << sumEven << endl;
	}
	system("pause");
}

int addEvenDigits(int num)
{
	if (num % 2 == 0)
	{
		num = num * num % 2 == 0;
	}
	else
	{
		return 0;
	}
		return num;
}
Last edited on
Ive tried your homework and i did it in less than 30 minutes or so?

this is what i do:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    int number = 3456;

    int trailingzeroes = 10;

    int sum = 0;
    for ( int a = 2; a < number*2; a*=10, trailingzeroes*=10 )
    {
            int ctr = 0;
            while( number%trailingzeroes != 0 )
            {
                --number;
                ++ctr;
            }
            ctr /= (trailingzeroes/10);
            if ( ctr % 2 == 0 )
            {
                sum+=ctr;
                std::cout << ctr << " + ";
            }
    }
    std::cout << "\b\b" << "= " << sum << std::endl;
}
Last edited on
I would do it like that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using std::cout;
using std::endl;

int input[]  = {1234, 222, 4567, 333};
int output[] = {6, 6, 10, 0};

#define NUM_ELEMS sizeof(input) / sizeof(input[0])

int SumOfEvenDigits(int num)
{
  int retval = 0, remainder = 0;

  while (num > 0)
  {
    remainder = num % 10;

    if (remainder % 2 == 0)
      retval += remainder;

    num = num / 10;
  }

  return retval;
}

int main()
{
  for (int i = 0; i < NUM_ELEMS; i++)
  {
    int val = SumOfEvenDigits(input[i]);

    cout << "input: " << input[i] << "\t" << "expected: " << output[i] << "\t" << "actual:" << val << endl << endl;
  }

  system("pause");
}
Thank you guys !! :)

I looked through my code and eventually solved it.

big Thanks for both of you!
Topic archived. No new replies allowed.