Sum of even numbers in 2D array

I am trying to sum only even numbers in a 2D array.
But I get the sum = 0, what's wrong with my code?
why is my for loops not doing anything?

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
#include <iostream>
using namespace std;

int main()
{
	const int MaxR = 3;
	const int MaxC = 3;
	int sum = 0, test, compare1;       //test = the value divided by 2,  compare1 = multiply test by 2 to see if it's the original value, if yes, add.
	int arr[MaxR][MaxC] = {
		{ 1, 2, 3 },
		{ 4, 5, 6 },
		{ 7, 8, 9 }};

	for (int i = 0; i < MaxR; i++)
	{
		for (int k = 0; k < MaxC; k++)
		{
			test = arr[i][k] / 2;
			compare1 = test * 2;

			if (arr[i][k] == compare1 * 2)
			{
				sum = sum + arr[i][k];
			}
		}
	}

	cout << sum;

	system("PAUSE");
	return 0;

}
Last edited on
You divide by 2 once (at line 18) but multiply by 2 twice (lines 19 and 21).


this would be simpler:
if (arr[i][k] % 2 == 0)
Well. If you would have debugged your code, you would have realized that the if statement is never true. That's now how you check whether a number is even or odd.

use the modulus operator - http://www.cprogramming.com/tutorial/modulus.html
to check if number is even:

if (arr[i][k] & 0)
Thank you guys. I never thought of it like this.

it works now.

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
#include <iostream>
using namespace std;

int main()
{
	const int MaxR = 3;
	const int MaxC = 3;
	int sum = 0;
	int arr[MaxR][MaxC] = {
		{ 1, 2, 3 },
		{ 4, 5, 6 },
		{ 7, 8, 9 }};

	for (int i = 0; i < MaxR; i++)
	{
		for (int k = 0; k < MaxC; k++)
		{
			if (arr[i][k] % 2 == 0)
			{
				sum = sum + arr[i][k];
			}
		}
	}

	cout << sum;

	getchar();
	return 0;

}
You can use at line 18:

 
sum += arr[i][k];
Last edited on
Topic archived. No new replies allowed.