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;
}
The code begins with the necessary header files
<iostream>
and<iomanip>
. Thestd
namespace is used for convenience.The
computeAverage
function is prototyped at the beginning to inform the compiler about its existence and signature. The function takes an array ofint
as a parameter and returns adouble
. TheARRAY_SIZE
is declared as a global constant variable representing the size of the array.In the
main
function, an arraystudentGrades
is declared to hold the grades of the students. The size of the array is determined by theARRAY_SIZE
constant.A
for
loop is used to prompt the user to enter the grades for each student. The loop iteratesARRAY_SIZE
times, and the user's input is stored in thestudentGrades
array.After collecting the grades, the program outputs the average by calling the
computeAverage
function and passing thestudentGrades
array as an argument. The average is computed and displayed usingcout
.The
computeAverage
function takes the arraypArray
as a parameter. It calculates the sum of all the grades using afor
loop. The sum is then divided byARRAY_SIZE
to compute the average. The average is returned as adouble
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