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:
#include <iostream>
: This line includes the necessary header file for input and output stream handling in C++.searchInArray
function: This function takes three parameters - an arrayarr
, its sizesize
, and akey
that needs to be found within the array. It iterates through the array elements using afor
loop and checks if the current element matches thekey
. If found, it returns the index of the element; otherwise, it returns-1
.main
function: In themain
function, an arrayarr
containing integers{2, 4, 6, 8, 10}
is declared. Thesize
variable is calculated as the total size of the array divided by the size of a single element in the array usingsizeof
. Thekey
variable is set to6
.result
variable: It stores the return value of thesearchInArray
function when called with the array, its size, and thekey
.Conditional check (
if-else
): It checks if theresult
is not-1
(which indicates the element was found). If the result is not-1
, it prints the index where thekey
was found in the array. Otherwise, it prints a message stating that the element was not found in the array.return 0
: It signifies the successful completion of the program's execution to the operating system.