Here is an object-oriented program in C++ that initializes an integer array of size 10, finds the sum and average of the array elements:
using namespace std;
class Array {
private:
int arr[10];
public:
void initialize() {
cout << "Enter 10 integer values: " << endl;
for(int i=0; i<10; i++) {
cin >> arr[i];
}
}
int sum() {
int s=0;
for(int i=0; i<10; i++) {
s += arr[i];
}
return s;
}
float average() {
int s = sum();
float avg = (float) s / 10.0;
return avg;
}
};
int main() {
Array a;
a.initialize();
cout << "Sum of array elements: " << a.sum() << endl;
cout << "Average of array elements: " << a.average() << endl;
return 0;
}
In this program, we define a class Array with a private data member arr that represents the array. The class has three public member functions - initialize(), sum() and average(). The initialize() function reads 10 integer values from the user and stores them in the array. The sum() function calculates and returns the sum of array elements using a for loop. The average() function calls the sum() function to calculate the sum and then calculates the average by dividing the sum by 10.0.
In the main() function, we create an object a of class Array, call the initialize() function to initialize the array, and then call the sum() and average() functions to find the sum and average of the array elements.
No comments:
Post a Comment
If you have any doubts, please let me know