0 votes
224 views
in Programming by (245 points)
edited
Implement a class average . Include a constructor in it which will accept value of three variables from user . Include two more functions in it one calculate average and other prints it

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer

#include <iostream>

using namespace std;

class Average {
   private:
      int num1, num2, num3;
      float avg;
      
   public:
      // Constructor to accept three values
      Average(int n1, int n2, int n3) {
         num1 = n1;
         num2 = n2;
         num3 = n3;
      }
      
      // Function to calculate average
      void calculateAverage() {
         avg = (num1 + num2 + num3) / 3.0;
      }
      
      // Function to print average
      void printAverage() {
         cout << "The average of " << num1 << ", " << num2 << ", and " << num3 << " is: " << avg << endl;
      }
};

int main() {
   // Create an instance of the "Average" class
   Average myAverage(5, 10, 15);
   
   // Calculate the average and print it
   myAverage.calculateAverage();
   myAverage.printAverage();
   
   return 0;
}
 

In the constructor, the values of num1, num2, and num3 are initialized with the values passed as arguments. The calculateAverage function calculates the average of these three numbers and stores it in the avg member variable. The printAverage function prints out the values of num1, num2, num3, and avg. In the main function, an instance of the "Average" class is created with the values 5, 10, and 15. The average is then calculated and printed out.

 

 

Related questions

0 votes
1 answer 195 views
0 votes
1 answer 1.2k views
0 votes
1 answer 230 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

559 users

...