Search Array Elements Program in C++

Google Advertisements

Prev Tutorial Next Tutorial

Search an Array Elements Program in C++

For search array element you need to compare all array element with that particular elements. In below C++ program we have to search an element in a given array using linear search algorithm. If given element is present in array then we will print it's index otherwise print a message saying element not found in array.

To understand this code you need basic knowledge about Array in C++ and For Loop in C++.

Linear Search in C++

In linear search algorithm, we compare targeted element with each element of the array. If the element is found then its position is displayed. The worst case time complexity for linear search is O(n).

Example

Input Array : [6, 12, 9, 8, 31, 10, 25]
Element to search : 31
Output : 
Element found at index 4

Search Array Elements Program in C

#include<iostream.h>
#include<conio.h>

void main()
{
int i,a[50],num,size;
clrscr();
cout<<"Enter size of array: ";
cin>>size;
cout<<"Enter any"<<size <<"element in array: \n";
for(i=0; i<size; i++)
{
cin>>a[i];
}
cout<<"Enter number for find their position: ";
cin>>num;
for(i=0; i<size; i++)
{
if(a[i]==num)
{
cout<<"\n index of "<<num <<" is " <<i;
}
}
getch();
}

Output

Enter size of array: 5
Enter any 5 elements in array:
20
40
30
50
10
Enter number for find their position: 50
index of 50 is 3

Note: Here we print number inxed value. That's why actual position of number is less than 1.

search array element program in c++
Prev Tutorial Next Tutorial

Google Advertisements

We have more than 5 Groups which have 500000+ Members and some Pages have more than 100000+ members. For Advertisement contact on [email protected] or 8076671483

Buy This Ad Space @$50 per Month, Ad Size 600X200 Contact on: [email protected] or 8076671483

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Classpath variable is set for providing a path for predefined Java classes which is used in our application. All classes are available in lib/rt.jar so we set classpath upto lib/rt.jar. Difference between path and classpath in Java

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user. Cloud Computing Tutorial

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects. Download Java C C++ Projects

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: [email protected] or 8076671483 Try this Keyword C++ Programs