Home »
C++ Programs
C++ program to find the sum of all elements of the array using class
Submitted by Shubh Pachori, on August 22, 2022
Problem statement
Given an array, we have to find the sum of all elements of the array using the class and object approach.
Example:
Input:
array[0]: 5
array[1]: 6
array[2]: 7
array[3]: 8
array[4]: 9
Output:
Sum of all elements of the array is 35
C++ code to find the sum of all elements of the array using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Array {
// private data member
private:
int 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];
}
}
// add() function to find the sum of all numbers of the array
int add() {
int sum = 0;
// for loop to add all elements of the array one by one
for (int index = 0; index <= 4; index++) {
sum = sum + array[index];
}
// returning the Sum
return sum;
}
};
int main() {
// create an object
Array A;
// int type variable to store the Sum of all numbers in it
int sum;
// function is called by the object to store the array
A.putArray();
// add() function to add all elements of the array
sum = A.add();
cout << "Sum of all elements of the array is " << sum;
return 0;
}
Output
array[0]:1
array[1]:2
array[2]:3
array[3]:4
array[4]:5
Sum of all elements of the array is 15
Explanation
In the above code, we have created a class Array, one int type array data member array[5] to store the values of the array, and public member functions putArray() and add() to store the given values in array and to find out the sum of all elements of the array.
In the main() function, we are creating an object A of class Array, reading an integer values by the user of the array using the putArray() function, and finally calling the add() member function to find the sum of all elements of the given array. The add() function contains the logic to find out the sum of all elements of the given array and printing the result.
C++ Class and Object Programs (Set 2) »