×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to find the mean of the array using class

Submitted by Shubh Pachori, on August 26, 2022

Problem statement

Given an array, we have to find the mean of the array using the class and object approach.

Example:

Input:
array[0]: 1
array[1]: 2
array[2]: 3
array[3]: 4
array[4]: 5

Output:
Mean of the array is 3 

C++ code to find the mean of the array using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Array {
  // private data member
  private:
    float array[5];

  // public functions
  public:
    // putArray() function to get the value of the array
    void putArray() {
      for (int index = 0; index <= 4; index++) {
        cout << "array[" << index << "]: ";
        cin >> array[index];
      }
    }

  // mean() function to find the mean of the array
  double mean() {
    // float type variable to performing operations
    float sum = 0, Mean;

    // int type variable for indexing
    int index;

    // for loop to add all elements of the array one by one
    for (index = 0; index <= 4; index++) {
      sum = sum + array[index];
    }

    // dividing sum by number of elements and 
    // storing in the variable Mean
    Mean = sum / 5;

    // returning the Mean
    return Mean;
  }
};

int main() {
  // create an object
  Array A;

  // float type variable to store the 
  // Mean of all numbers in array
  float Mean;

  // function is called by the object to 
  // store the array
  A.putArray();

  // mean() function to find out the 
  // mean of the array
  Mean = A.mean();

  cout << "Mean of the array is " << Mean;

  return 0;
}

Output

RUN 1:
array[0]: 1 
array[1]: 22
array[2]: 333
array[3]: 4444
array[4]: 55555
Mean of the array is 12071

RUN 2:
array[0]: 10
array[1]: 20
array[2]: 30
array[3]: 40
array[4]: 50
Mean of the array is 30

Explanation

In the above code, we have created a class Array, one int type array data member array[5] to store the values, and public member functions putArray()" and "mean() to store the given values in an array and to find out the mean of the array.

In the main() function, we are creating an object A of class Array, reading integer values by the user of the array using the putArray() function, and finally calling the mean() member function to find out the mean of the array. The mean() function contains the logic to find out the mean of the array and printing the result.

C++ Class and Object Programs (Set 2) »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.