Demo - One-Dimensional Array

// Demo of an array of int grades and the resulting average #include <iostream> #include <iomanip> using namespace std; //prototype a function to compute the average double computeAverage(int[]); const int ARRAY_SIZE = 5; //global variable for Array Size int main() { // Declare variables int studentGrades[ARRAY_SIZE]; //lsit of 5 student grades in an array //use a for loop to ask for the 5 grades for(int i = 0; i < ARRAY_SIZE; i++) { cout << "Enter grade number "<< (i + 1) << "; "; cin >> studentGrades[i]; } //output the student average cout << showpoint << fixed << setprecision(2); cout << "The grade average is " << computeAverage(studentGrades) << endl; return 0; } //end of main // function takes an array and computes the average double computeAverage(int pArray[]) { int mySum = 0; double myAverage = 0.0; for(int i = 0; i < ARRAY_SIZE; i++) { mySum += pArray[i]; } myAverage = static_cast<double>(mySum) / ARRAY_SIZE; return myAverage; }
  1. The code begins with the necessary header files <iostream> and <iomanip>. The std namespace is used for convenience.

  2. The computeAverage function is prototyped at the beginning to inform the compiler about its existence and signature. The function takes an array of int as a parameter and returns a double. The ARRAY_SIZE is declared as a global constant variable representing the size of the array.

  3. In the main function, an array studentGrades is declared to hold the grades of the students. The size of the array is determined by the ARRAY_SIZE constant.

  4. A for loop is used to prompt the user to enter the grades for each student. The loop iterates ARRAY_SIZE times, and the user's input is stored in the studentGrades array.

  5. After collecting the grades, the program outputs the average by calling the computeAverage function and passing the studentGrades array as an argument. The average is computed and displayed using cout.

  6. The computeAverage function takes the array pArray as a parameter. It calculates the sum of all the grades using a for loop. The sum is then divided by ARRAY_SIZE to compute the average. The average is returned as a double value.

When the code is executed, it prompts the user to enter the grades for each student and then calculates and displays the average of the grades.

COSC-1336 / ITSE-1302 Computer Science - Author: Dr. Kevin Roark