//global constants const int candidates=3; const int states=50; //function to count the votes of a candidate int candidate_sum (int votes[][states], int candidate){ int i, sum=0; //loop over the states for this candidate for (i=0; i<states; i++) sum += votes[candidate][i]; return sum; } Prototype: int candidate_sum (int [][states], int); int polls[candidates][states]; //gather the votes... //then count a candidate's total votes cout << "Which candidate to count votes of: "; cin >> candidate; total = candidate_sum(polls,candidate); cout << "Candidate " << candidate << " got " << total << " votes"; //sum votes for each candidate for (cand=0; cand< candidates; cand++) cout << "Candidate " << cand << " got " << candidate_sum(polls,cand); ------------------------------------------------------- //function to count the votes of a state int state_sum (int votes[][states], int state) { int i, sum=0; //loop over the candidates for this state for (i=0; i<candidates; i++) sum += votes[i][state]; return sum; } Prototype: int state_sum (int [][states], int); //sum of each states votes, into array int state_totals[states]; for (i=0; i<states; i++) state_totals[i] = state_sum(polls,i); -------------------------------------------- //function to count the votes of each candidate, // into array argument. void count_votes (int votes[][states], int sum[]) { int i, j; for (i=0; i<candidates; i++) //initialize candidate sums to 0 sum[i] = 0; for (i=0; i<candidates; i++) //loop over rows/candidates for (j=0; j<states; j++) //loop over columns/states sum[i] += votes[i][j]; } Prototype: void count_votes (int [][states], int []); //sum of each states votes, into array int totals[candidates]; count_votes(polls,totals); for (i=0; i< candidates; i++) cout << "Candidate " << i << " got " << totals[i] << "votes" << endl; ------------------------------------------------------- //2D array of grades. //rows are students, columns are their grades char grades[max_students][max_grades]; //sized by constants //call function to input one grade for one student get_grade(grades); //2D array of chars whose 2nd dim. // size is max_grades //definition of the get_grade function: void get_grade (char GR[][max_grades]) { int student, exam; //row and col do { cout << "Enter student number: "; cin >> student; if (student > max_students) cout << "Error. Must be <= " << max_students; } while (student > max_students); do { cout << "Enter exam number: "; cin >> exam; if (exam > max_grades) cout << "Error. Must be <= " << max_grades; } while (exam > max_grades); GR[student][exam] = get_valid_grade(); //returns valid grade } function to get all exams of a student function to get all exams of all students function to calculate gpa of a student function to display grades of a student function to read file of lines of grades, return #rowsProgram to move a "mouse" around the screen. move_mouse.cpp
Next (row of a 2D array)