Skip to content
doubtly

Implement a class average . Include a constructor in it which will accept value of three variables from user

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
Roll D. Asked Updated Student doubt c++ Save WhatsApp Report

2 answers

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.

Doubtly · 7 Mar 2023 Report
Was this answer helpful?

Answer: The constructor below reads the three values from the user with cin; one member function calculates the average and another prints it.

#include <iostream>
using namespace std;

class average
{
    float a, b, c, avg;
public:
    average()                 // constructor
    {
        cout << "Enter three numbers: ";
        cin >> a >> b >> c;
    }
    void calculate()
    {
        avg = (a + b + c) / 3;
    }
    void display()
    {
        cout << "Average = " << avg << endl;
    }
};

int main()
{
    average obj;      // constructor runs and takes input
    obj.calculate();
    obj.display();
    return 0;
}

How it works:

  • When the object obj is created, the constructor average() is called automatically and reads the three numbers from the keyboard.
  • calculate() finds \((a+b+c)/3\) and stores it in avg. The variables are float, so the result is not truncated.
  • display() prints the average.

Sample run: entering 4 5 9 prints Average = 6.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.