Array Example

//  this program reads 10 grades into an array, then calculates the average
//  grade and the highest grade

#include <iostream.h>
#include <iomanip.h>

int main()
{
   int grades[10];
   int sum = 0;
   float average;
   int max;

//  set up output to print floating point values with one decimal place
    cout << setiosflags(ios::fixed);
    cout << setiosflags(ios::showpoint);
    cout << setprecision(1);

//  read in the grades and add them up
   for (int i = 0 ; i < 10 ; i++)
   {
      cout << "Enter grade: ";
      cin >> grades[i];
      sum = sum + grades[i];
   }

//  calculate the average grade
   average = float(sum) / 10;

//  find the highest grade
   max = grades[0];
   for (i = 1 ; i < 10 ; i++)
      if (max < grades[i])
         max = grades[i];

//  print the grades, the average and the highest
   cout << "The grades are: " << endl;
   for (i = 0 ; i < 10 ; i++)
      cout << setw(7) << grades[i] << endl;
   cout << endl << "The highest grade is " << max << endl;
   cout << endl << "The average grade is " << average << endl;

   return 0;
}

Sample Execution

Enter grade: 82
Enter grade: 74
Enter grade: 86
Enter grade: 92
Enter grade: 94
Enter grade: 78
Enter grade: 85
Enter grade: 90
Enter grade: 81
Enter grade: 77
The grades are:
     82
     74
     86
     92
     94
     78
     85
     90
     81
     77

The highest grade is 94

The average grade is 83.9


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002