Program : Check if an array contains a specific element in C++.
Solution :
#include <iostream> using namespace std; bool containsElement(int array[], int size, int target) { for (int i = 0; i < size; i++) { if (array[i] == target) { return true; // Element found } } return false; // Element not found } int main() { const int size = 5; int arr[size], i, target; cout << "Enter the elements of the array: "; for (i = 0; i < size; i++) { cin >> arr[i]; } cout << "Enter the element to search: "; cin >> target; if (containsElement(arr, size, target)) { cout << "Element " << target << " is found in the array." << std::endl; } else { cout << "Element " << target << " is not found in the array." << std::endl; } return 0; }
Output :
Enter 5 elements of an array: 2 4 6 8 10 Enter the element to search: 6 Element 6 is found in the array.
Dry Run :
Let’s walk through the code written inside the containsElement() function :
i | i<size | array[i] | target | Match? | i++ | return value |
0 | True | 2 | 6 | No | 1 | |
1 | True | 4 | 6 | No | 2 | |
2 | True | 6 | 6 | Yes | 3 | true |
So, the element 6 is found in the array, and the function “containsElement()” returns true. If you want to display the position or index of the target element then change the function return type i.e. bool to int and if element is found then return “i” instead of true, otherwise return -1.
Want to practice more problems involving Array 1-D ? Click here.
1 comment
I wanted to thank you for this very good read!! I absolutely loved every bit of it. Ive got you saved as a favorite to check out new things you postÖ