How to Search an Element in an Array
Here you will learn and get the example code of C++ program to search an element in an array list. This is an example of single dimensional array to search the location of a specific array element, If exist in the array list.
Example of C++ Program to Search an Element in an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include<iostream> using namespace std; int main() { int j, k=0, loc=0, arr[5], item; cout<<"\nInput 5 Numbers : "; for(j=0; j<5;j++) { cin>>arr[j]; } cout<<"\nEnter the element to search in the array :"; cin>>item; while(loc==0 && k<5) { if(item==arr[k]) loc=k+1; else k++; } if(loc==0) cout<<item<<" is not found in array"; else cout<<item<<" found at location of "<<loc; return 0; } |
Output
Input Five Numbers : 2
4
6
8
12
Enter the element to search in the array : 6
6 found at location of 3
Check out our other C++ programming Examples