Search an Element in an array in C++ Programming


Number of elements in array as input from user and store it in a variable N. Using a loop, take N numbers as input from user and store it in array. Ask user to enter element to be searched let if be num. If num is equal to any array element then print.

This program allows the user to enter the size of an array and its elements, and then searches for a specific value in the array:

  • Declare an integer array a with a maximum size of 100, and integer variables n, i, and x.
  • Ask the user to enter the size of the array and store it in n.
  • Use a for loop to iterate through each index of the array up to n.
  • For each index, ask the user to enter the corresponding element of the array and store it in a[i].
  • Ask the user to enter the value to search for and store it in x.
  • Use another for loop to iterate through each index of the array up to n.
  • For each index, check if the corresponding element of the array (a[i]) is equal to x.
  • If a[i] is equal to x, print a message indicating that the value was found at index i and return from the program.
  • If the loop completes without finding x, print a message indicating that the value was not found and return from the program.

Note that this program only searches for the first occurrence of x in the array. If there are multiple occurrences of x, only the first one will be reported.

Source Code

#include<iostream>
using namespace std;
//Program to find a number in an array.
int main()
{
    int a[100],n,i,x;
    cout<<"\nEnter The Limit: ";
    cin>>n;
    for(i=0;i<n;i++)
    {
        cout<<"\nEnter The Value : ";
        cin>>a[i];
    }
    cout<<"\nEnter The Value to Search :";
    cin>>x;
 
    for(i=0;i<n;i++)//1 2 3 4 5
    {
        if(a[i]==x)
        {
            cout<<"Value Found @"<<i;
            return 0;
        }
    }
    cout<<"Value Not Found";
    return 0;
}
 

Output

Enter The Limit: 5

Enter The Value : 23

Enter The Value : 45

Enter The Value : 56

Enter The Value : 78

Enter The Value : 45

Enter The Value to Search :56
Value Found @2
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples