C++ Program to Search Element in Array



C++ Program to Search Element in Array | ninjasquad

In this tutorial, you’ll learn about array operation for search element in array. We will perform search operations on the unsorted array and find elements in the array using C++.

The complexity of the search element in an unsorted array in the worst case is O(n).

C++ program to search an element in an array


#include<iostream>
using namespace std;

int main(){
	
	int n,x,flag=0;
	cout<<"Enter the Size of Array : \n";
	cin>>n;
	int i,arr[n];
	cout<<"Enter the Array Elements : \n";
		for(i=0; i<n; i++){
			cin>>arr[i];
		}
	cout<<"Enter the Element to Search in Array : \n";
	cin>>x;
		for(i=0; i<n; i++){
			if(arr[i]==x){
				flag=1;
			}
		}
		
	if(flag==1){
		cout<<"Element present in array at "<<i<<endl;
	}else{
		cout<<"Element not present in array"<<endl;	
	}
	return 0;
}

Output

Enter the Size of Array :
 4
 Enter the Array Elements :
 23
 54
 67
 32
 Enter the Element to Search in Array :
 32
 Element present in array at 4

Enter the Size of Array :
 4
 Enter the Array Elements :
 23
 54
 33
 64
 Enter the Element to Search in Array :
 12
 Element not present in array

Above article, you learn about array operation for search element in array. If you have any doubt then comment.



Source: Internet

Leave a Comment

We are offering free coding tuts

X