int votes[3][50]; //3 rows (candidates), 50 columns (states)
// initialize the votes array Nested for loops is typical processing of 2D array
for (row=0; row<3; row++) // each row
for (col=0; col<50; col++) // each column, of that row
votes[row][col] = 0;
// get votes of a candidate in a state from user
cout << "Enter state number: ";
cin >> state;
cout << "Enter candidate number: ";
cin >> candidate;
// should error check these values to be sure within bounds of sizes
cout << "Enter votes rececived: ";
cin >> votes[candidate][state];
// sum of candidate 1
sum_cand1 = 0;
for (i=0; i<50; i++) // each state (each column of row 1)
sum_cand1 += votes[1][i];
const int states=50, candidates=3;
int votes[candidates][states];
// initialize all elements to 0
for (i=0; i< candidates; i++) //common to use i for row
for (j=0; j< states; j++) //common to use j for column
votes[i][j] = 0;
// sum of state 9
sum_state9 = 0;
for (i=0; i< candidates; i++)
sum_state9 += votes[i][9];
// sum of state 9, alternate version, not as good
sum_state9 = votes[0][9] + votes[1][9] + votes[2][9];
// sum of votes for each candidate
int sum[candidates];
for (i=0; i< candidates; i++) //init sums to 0
sum[i] = 0;
for (i=0; i< candidates; i++)
for (j=0; j< states; j++)
sum[i] += votes[i][j];
// the winner is...
if (sum[0]>sum[1] && sum[0]>sum[2])
cout << "Winner is 0";
else if (sum[1]>sum[0] && sum[1]>sum[2])
cout << "Winner is 1";
else
cout << "Winner is 2";
// What if there is a tie for winner?
// What is the order of the 3 candidates?
Program to (start) to play checkers. checkers.cpp
Next (2D array arguments)