c++ find index of element in array
Code Example:
#include <iostream>
int findIndex(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {4, 7, 2, 8, 5};
int target = 2;
int size = sizeof(arr) / sizeof(arr[0]);
int index = findIndex(arr, size, target);
if (index != -1) {
std::cout << "Element found at index: " << index << std::endl;
} else {
std::cout << "Element not found in the array" << std::endl;
}
return 0;
}
Explanation:
- Include the necessary header file:
#include <iostream>
- This line includes the input/output stream library which provides functionality for input and output through streams, such asstd::cout
andstd::cin
.Define the function to find the index of the element in the array:
int findIndex(int arr[], int size, int target)
- This function takes an array, its size, and the target element as parameters and returns the index of the target element in the array.Iterate through the array:
for (int i = 0; i < size; i++)
- This loop iterates through the elements of the array using the index variablei
.Check for the target element:
if (arr[i] == target)
- This condition checks if the current element in the array is equal to the target element.Return the index if the element is found:
return i;
- If the target element is found, the function returns the index at which the element is located in the array.Return -1 if the element is not found:
return -1;
- If the loop completes without finding the target element, the function returns -1 to indicate that the element is not present in the array.Main function to test the findIndex function:
int main()
- This is the entry point of the program where thefindIndex
function is tested.Create an array and define the target element:
int arr[] = {4, 7, 2, 8, 5};
- An array namedarr
is created with some elements.int target = 2;
- The target element to be searched for is defined as 2.Calculate the size of the array:
int size = sizeof(arr) / sizeof(arr[0]);
- The size of the array is calculated using the sizeof operator.Call the findIndex function and display the result:
int index = findIndex(arr, size, target);
- ThefindIndex
function is called with the array, its size, and the target element.if (index != -1)
- If the returned index is not -1 (indicating the element was found), a message displaying the index is printed.else
- If the index is -1, a message indicating that the element was not found is printed.Return 0 to indicate successful completion of the program.