C++ program to find the largest number of an array using class

Given an array of integer, we have to find the find the largest number of an array using class and object approach.
Submitted by Shubh Pachori, on August 06, 2022

Example:

Input: 
array[0]: 1
array[1]: 2
array[2]: 44
array[3]: 3
array[4]: 5

Output:
Largest Number is 44

C++ code to find the largest number of an array using 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];
    }
  }

  // largest() function to find the largest number in the array
  int largest() {
    // let the first element of the array is max
    int max = array[0];

    // for loop to read the whole array from the second term to the second
    for (int index = 1; index <= 4; index++) {
      // if the value at the index is greater than the max then the value
      // will replace the value at the max
      if (array[index] > max) {
        max = array[index];
      }
    }

    // returning the largest number
    return max;
  }
};

int main() {
  // create an object
  Array A;

  // int type variable to store the largest number in it
  int max;

  // function is called by the object to store the array
  A.putArray();

  // largest() function is called by the object to find the
  // largest value in the array
  max = A.largest();

  cout << "Largest Number is " << max;

  return 0;
}

Output

RUN 1:
array[0]:33
array[1]:333
array[2]:11
array[3]:1111
array[4]:44
Largest Number is 1111

RUN 2:
array[0]:12
array[1]:34
array[2]:56
array[3]:10
array[4]:5
Largest Number is 56

Explanation:

In the above code, we have created a class Array, one int type array data member array[5] to store the values, and public member functions puArray() and largest() to store the given values in an array and to find the largest one.

In the main() function, we are creating an object A of class Array, reading integer values by the user of the array using the putArray() function, and finally calling the largest() member function to find the largest number in the given integer number in the array. The largest() function contains the logic to find the largest number in the given numbers and printing the result.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.