C++ Program to search an element in an array using the function


In this program, You will learn how to search an element in an array using the function in C++.


List is :2 3 4 5 10 33 44 55 66

Enter number for search: 44

The number found: 44

Example: How to search an element in an array using a function in C++.

#include<iostream>
using namespace std;

void findNumber(int array[], int size, int num) {

    int f = 0;

    for (int i = 0; i < size; i++) {
        if (num == array[i]) {
            f = 1;
            break;
        }
    }

    if (f == 1) {
        cout << "Element Found:" << num;
    } else {
        cout << "Element not found:" << num;
    }
}

int main() {

    int array[10], i, size, num;

    cout << "Enter size of an array:";
    cin>>size;

    cout << "Enter array elements:";
    for (i = 0; i < size; i++) {
        cin >> array[i];
    }

    cout << "Enter number for search:";
    cin>>num;

    findNumber(array, size, num);

    return 0;
}

Output:

Enter size of an array:5
Enter array elements:10 20 30 40 50
Enter number for search:40
Element Found:40