Write a c++ Program to get the average marks of six subjects using the Multiple Inheritance
Certainly! Below is an example of a C++ program that demonstrates multiple inheritance to calculate the average marks of six subjects. In this example, we'll create two base classes: `SubjectMarks` for storing marks of each subject, and `AverageCalculator` for calculating the average. The derived class `Student` will inherit from both of these base classes.
```cpp
#include <iostream>
using namespace std;
// Base class for storing subject marks
class SubjectMarks {
protected:
float marks[6]; // Array to hold marks for six subjects
public:
void inputMarks() {
cout << "Enter marks for 6 subjects (0-100):\n";
for (int i = 0; i < 6; i++) {
cout << "Subject " << (i + 1) << ": ";
cin >> marks[i];
// Input validation
while(marks[i] < 0 || marks[i] > 100) {
cout << "Invalid marks! Please enter again for Subject " << (i + 1) << ": ";
cin >> marks[i];
}
}
}
};
// Base class for calculating average
class AverageCalculator {
public:
float calculateAverage(float marks[], int numberOfSubjects) {
float sum = 0;
for (int i = 0; i < numberOfSubjects; i++) {
sum += marks[i];
}
return sum / numberOfSubjects;
}
};
// Derived class
class Student : public SubjectMarks, public AverageCalculator {
public:
void displayAverage() {
// Calculate average
float average = calculateAverage(marks, 6);
cout << "The average marks of the six subjects is: " << average << endl;
}
};
int main() {
Student student; // Create a Student object
student.inputMarks(); // Input marks for the subjects
student.displayAverage(); // Calculate and display the average
return 0;
}
```
### Explanation:
1. **SubjectMarks Class**: This class holds the marks for the six subjects and provides a method `inputMarks()` to input the marks.
2. **AverageCalculator Class**: This class contains a method `calculateAverage()` which takes an array of marks and the number of subjects, then calculates and returns the average.
3. **Student Class**: This derived class inherits from both `SubjectMarks` and `AverageCalculator`. It contains a method `displayAverage()` that retrieves the marks and calculates the average using the inherited method.
4. **Main Function**: In the `main()` function, we create an instance of `Student`, call the `inputMarks()` method to get marks from the user, and then call `displayAverage()` to calculate and display the average marks.
### Compilation and Execution:
To compile and run the program:
1. Save the code in a file named `average_marks.cpp`.
2. Open a terminal and navigate to the directory where the file is saved.
3. Compile the program using: `g++ average_marks.cpp -o average_marks`
4. Run the executable: `./average_marks`
This way, you can input the marks for six subjects and get the average displayed.