Linear Search in C++
To search any element present inside the array in C++ programming using linear search technique, you have ask to the user to enter the array size and array elements to store the elements in the array. Now ask to the user to enter the element that he/she want to check or search whether the entered number/element is present in the array or not.
To check/search for the element, just compare with the number to each element present in the array if any element equal to the entered number then print the exact position of the number in the array as shown here in the following program.
C++ Programming Code for Linear Search
Following C++ program first ask to the user to enter the array size then it will ask to enter the array elements, then it will finally ask to enter a number to be search in the given array to check whether it is present in the array or not, if it is present then at which position :
/* C++ Program - Linear Search */ #include<iostream.h> #include<conio.h> void main() { clrscr(); int arr[10], i, num, n, c=0, pos; cout<<"Enter the array size : "; cin>>n; cout<<"Enter Array Elements : "; for(i=0; i<n; i++) { cin>>arr[i]; } cout<<"Enter the number to be search : "; cin>>num; for(i=0; i<n; i++) { if(arr[i]==num) { c=1; pos=i+1; break; } } if(c==0) { cout<<"Number not found..!!"; } else { cout<<num<<" found at position "<<pos; } getch(); }
When the above C++ program is compile and executed, it will produce the following result: