Friday, April 28, 2017

Calculating Average Using OOP (C++)

# include<iostream>
#include<conio.h>
using namespace std;

class array{
    float *f_a;
    public:
    array(int);
    ~array();
    void getdata(int);
    float average(int);
};

array::array(int k){
    f_a=new float[k];
    if(!f_a){
        cout<<"Allocation failure."<<endl;
    }
}

array::~array(){
    delete[]f_a;
}

void array::getdata(int l){
    cout<<"Enter "<<l<<" elements: ";
    for(int i=0; i<l;i++){
        cin>>f_a[i];
    }
}

float array::average(int m){
    float sum;
    for(int j=0;j<m;j++){
        sum+=f_a[j];
    }
    return(sum/m);
}

int main(){
    int n;
    cout<<"Number of elements: ";
    cin>>n;
    array f(n);
    f.getdata(n);
    cout<<"The average is: "<<f.average(n)<<endl;
    return 0;
}

No comments:

Post a Comment