C++ Programming Code Examples C++ > Sorting Searching Code Examples Linear search in C++ Program Code Linear search in C++ Program Code Linear search or sequential search is one of the searching algorithm in which we have some data in a data structure like array data structure and we have to search a particular element in it which is know as key. By traversing the whole data structure elements from start to end one by one to find key comparing with each data structure element to the key. In case of an array we check that the given key or a number is present in array at any index or not by comparing each element of array There can be two possible outcomes if we are assuming that data structure like array contains unique values. Linear search successful Key Found means in array at an index we found value which matches to our key Linear search failed to find the Key mean our key does not exist in data To Make Logic First We Think That We Have To Traverse Whole Array Form Start To End So we Decide To Use a Loop First for Loop Taking Input in Array Element By Element Second Displaying Entered Elements Third for Loop Which is Main For Loop Having an if Condition Which Checks Every Array Element with Key If an Element Matches With Key if Condition Becomes True and Loop Terminates With Break Statement Then If Condition Outside Loop Which Will Become True Because Loop Variable 'i' not Equal to Size Of Array If Element Not Found In Array Than Loop Will Run Complete And If Condition Will Not True Because in This Case Loop Will Run Complete And After Termination Variable 'i' Will be Equal to Size Variable #include<iostream> using namespace std; int main() { cout<<"Enter The Size Of Array: "; int size; cin>>size; int array[size], key,i; // Taking Input In Array for(int j=0;j<size;j++){ cout<<"Enter "<<j<<" Element: "; cin>>array[j]; } //Your Entered Array Is for(int a=0;a<size;a++){ cout<<"array[ "<<a<<" ] = "; cout<<array[a]<<endl; } cout<<"Enter Key To Search in Array"; cin>>key; for(i=0;i<size;i++){ if(key==array[i]){ cout<<"Key Found At Index Number : "<<i<<endl; break; } } if(i != size){ cout<<"KEY FOUND at index : "<<i; } else{ cout<<"KEY NOT FOUND in Array "; } return 0; }