C++ | Searching an Element in Array

Introduction.

This is a tutorial for searching a element in array list in C++. The program takes the array list from user and asks the user to enter the number to be searched, its continues and tell the position of the element or not found message. The program has lots of applications. Go enjoy the program. Lets begin….

Program for Searching a element in array.

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare array and var.
int a[10],no;
//Add a loop to fill the array.
for(int i=0;i<10;i++)
{
cout<<"Enter the no."<<endl;
cin>>a[i];
}
//the number to searched
cout<<"Enter the number to be searched"<<endl;
cin>>no;
//find the number
for(i=0;i<10;i++)
{
if(a[i]==no)
break;
}
//The output
if(i==10)
cout<<"Number not found"<<endl;
else
cout<<"The Number is at "<<i+1<<" position";
//get character
getch();
}

Output

Enter the no:
12
Enter the no:
13
Enter the no:
14
Enter the no:
15
Enter the no:
16
Enter the no:
17
Enter the no:
18
Enter the no:
19
Enter the no:
20
Enter the no:
21
Enter the number to be searched
16
The number is at 5 position.

How does it work.

  1. You enter the number in array and enter the number to be searched.
  2. The number is searched and the result is printed.

Extending it.

The program is extendable as you wish or your requirement.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare variables and array.
  5. Add cout and cin to get array and number.
  6. Search the number
  7. Print the result.
  8. Get character.

At the end

You learnt creating the C++ program for Searching a element in array. So now enjoy the program.

Please  share it.

Sharing options: