Lab 10 Exercise 1 Solution

Calculate average marks exercise with exception handling and pre conditions and post conditions

#include <iostream>
using namespace std;
 
class OutOfRangeException {};
 
/*
 * Pre conditions: all the four marks must be between
 * 0 -100 otherwise the function throws a OutOfRangeException
 * Post condition: returns the average of the four marks
 * Invariants: avg >= 0 && avg <=100
 */
float calculateAverage(int m1, int m2, int m3, int m4) {
      if ((m1 < 0 || m1 > 100))
         throw OutOfRangeException();
      if (m2 < 0 || m2 > 100)
         throw OutOfRangeException();
      if (m3 < 0 || m3 > 100)
         throw OutOfRangeException();
      if (m4 < 0 || m4 > 100)
         throw OutOfRangeException();
 
      return (m1 + m2 + m3 +m4 ) / 4.0;
}
 
int main () {
    try {
        float avg = calculateAverage(79,90,100,90);
        cout << avg;
    }catch (OutOfRangeException ) {
        cerr << "marks out of range" << endl;
    }
    system("pause");
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License