Write a C++ program using the concept of OOP to find the maximum and minimum element in an array


 Here is an example algorithm and C++ program that finds the maximum and minimum element in an array using the concept of object-oriented programming (OOP):

Algorithm:

  1. Create a class called "Finder"
  2. Define two private variables, one for max element and one for min element
  3. Define a public function called "find_min_max()" that takes in an array of integers as an input
  4. Initialize the max and min variables to the first element of the array
  5. Iterate through the input array and use if statements to check if the current element is greater than the max value or less than the min value
  6. If the current element is greater than the max value, update the max value
  7. If the current element is less than the min value, update the min value
  8. Define a public function called "print_min_max()" that prints out the min and max values

C++ Program:

#include <iostream>
 
class Finder {
private:
    int min_element;
    int max_element;
 
public:
    void find_min_max(int input_array[], int size) {
        min_element = input_array[0];
        max_element = input_array[0];
        for (int i = 1; i < size; i++) {
            if (input_array[i] > max_element) {
                max_element = input_array[i];
            }
            if (input_array[i] < min_element) {
                min_element = input_array[i];
            }
        }
    }
 
    void print_min_max() {
        std::cout << "Minimum element: " << min_element << std::endl;
        std::cout << "Maximum element: " << max_element << std::endl;
    }
};
 
int main() {
    int input_array[] = {5, 2, 8, 1, 9, 3};
    int size = sizeof(input_array) / sizeof(input_array[0]);
 
    Finder finder;
    finder.find_min_max(input_array, size);
    finder.print_min_max();
 
    return 0;
}
 
 
/*
======Input/Output=====
int input_array[] = {5, 2, 8, 1, 9, 3};
Minimum element: 1
Maximum element: 9
*/

#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment