how to search in array c++

#include <iostream>

int searchInArray(int arr[], int size, int key) {
    for (int i = 0; i < size; ++i) {
        if (arr[i] == key) {
            return i;
        }
    }
    return -1;
}

int main() {
    int arr[] = { 2, 4, 6, 8, 10 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int key = 6;

    int result = searchInArray(arr, size, key);

    if (result != -1) {
        std::cout << "Element found at index: " << result << std::endl;
    } else {
        std::cout << "Element not found in the array" << std::endl;
    }

    return 0;
}

Explanation:

  1. #include <iostream>: This line includes the necessary header file for input and output stream handling in C++.

  2. searchInArray function: This function takes three parameters - an array arr, its size size, and a key that needs to be found within the array. It iterates through the array elements using a for loop and checks if the current element matches the key. If found, it returns the index of the element; otherwise, it returns -1.

  3. main function: In the main function, an array arr containing integers {2, 4, 6, 8, 10} is declared. The size variable is calculated as the total size of the array divided by the size of a single element in the array using sizeof. The key variable is set to 6.

  4. result variable: It stores the return value of the searchInArray function when called with the array, its size, and the key.

  5. Conditional check (if-else): It checks if the result is not -1 (which indicates the element was found). If the result is not -1, it prints the index where the key was found in the array. Otherwise, it prints a message stating that the element was not found in the array.

  6. return 0: It signifies the successful completion of the program's execution to the operating system.