×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to search an element (number) in array using class

Submitted by Shubh Pachori, on September 14, 2022

Problem statement

Given an integer array, we have to search a given number in array using the class and object approach.

Example:

Input:
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10

Output:
Enter Number you want to search: 1
Number is present!

C++ code to search an element (number) in array using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Array {
  // private data member
 private:
  int arr[10];

  // public member functions
 public:
  // getArray() function to insert 
  // array elements
  void getArray() {
    for (int index = 0; index < 10; index++) {
      cout << "[" << index << "]: ";
      cin >> arr[index];
    }
  }

  // searchNumber() function to search Number
  // is present in the array or not
  void searchNumber() {
    // initialising int type variables
    // to perform operations
    int number, index, count = 0;

    // inserting number
    cout << "\nEnter Number you want to search: ";
    cin >> number;

    // for loop to traverse the whole array
    for (index = 0; index < 10; index++) {
      // if condition to check for the inserted number
      if (number == arr[index]) {
        count++;
        break;
      } else {
        count = 0;
      }
    }

    if (count != 0) {
      cout << "\nNumber is present!" << endl;
    } else {
      cout << "\nNumber is not present!" << endl;
    }
  }
};

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

  // calling getArray() function to 
  // insert the array
  A.getArray();

  // calling searchNumber() function to find
  // the number in the array
  A.searchNumber();

  return 0;
}

Output

[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10

Enter Number you want to search: 1

Number is present!

Explanation

In the above code, we have created a class Array, one int type array data members arr[10] to store the elements of the array, and public member functions getArray() and searchNumber() to store the array elements and to search the number in the array.

In the main() function, we are creating an object A of class Array, reading the inputted array by the user using getArray() function, and finally calling the searchNumber() member function to search the number in the array. The searchNumber() function contains the logic to search the number in the array and printing the result.

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

Comments and Discussions!

Load comments ↻





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