Sample Program: For Loop

//  This program calculates the average of a set of exams.
//  The program will read in exactly 8 grades, then calculate and
//  print the average.

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

int main()
{
   int grade;
   int numberOfGrades = 0;
   int totalGrades;
   float averageGrade;

//  read in the grades, total them, and count how many grades there are
   for (numberOfGrades = 0 ; numberOfGrades < 8 ; numberOfGrades++)
   {
      cout << "Enter the next exam score: ";
      cin >> grade;
      totalGrades = totalGrades + grade;
   }

//  calculate and print the average
   averageGrade = float(totalGrades) / numberOfGrades;
   cout << setiosflags(ios::fixed);
   cout << setiosflags(ios::showpoint);
   cout << setprecision(1);
   cout << "The average grade for the exam is :  " << averageGrade << endl;
}

Sample Execution

Enter the next exam score: 82
Enter the next exam score: 91
Enter the next exam score: 96
Enter the next exam score: 77
Enter the next exam score: 85
Enter the next exam score: 95
Enter the next exam score: 71
Enter the next exam score: 88
The average grade for the exam is :  85.6


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

© Copyright Emmi Schatz 2002