Write a C++ program using the concept of OOP to find the sum of all elements of the array


 Write a C++ program using the concept of OOP to find the sum of all elements of the array

Algorithm:

  1. Create a class called "SumFinder"
  2. Define a private variable called "sum" to keep track of the sum of the elements
  3. Define a public function called "find_sum()" that takes in an array of integers as an input
  4. Iterate through the input array and add each element to the sum variable
  5. Define a public function called "print_sum()" that prints out the sum of the elements in the array

C++ Program:

#include <iostream>
 
class SumFinder {
private:
    int sum = 0;
 
public:
    void find_sum(int input_array[], int size) {
        for (int i = 0; i < size; i++) {
            sum += input_array[i];
        }
    }
 
    void print_sum() {
        std::cout << "Sum of the elements: " << sum << std::endl;
    }
};
 
int main() {
    int input_array[100];
    int size;
    std::cout << "Enter the number of elements in the array: ";
    std::cin >> size;
    std::cout << "Enter the elements of the array: ";
    for(int i = 0; i< size; i++){
        std::cin >> input_array[i];
    }
 
    SumFinder finder;
    finder.find_sum(input_array, size);
    finder.print_sum();
 
    return 0;
}
 
 
 
/*
======Input/Output=====
Enter the number of elements in the array: 5
Enter the elements of the array: 1 2 3 4 5
Sum of the elements: 15
*/


#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment