Check if a value exists in an array in C++

In this tutorial, we will learn how to check the presence of a value in an array in C++. So let’s get started.

An array is a group of similar types of data items that can be int, float, or string. These elements are stored in an adjacent memory location. Always remember that by default the array index starts with Zero.

How to check if a value exists in an array in C++?

Now I will show you how you can easily check for a value. This can be done by following simple steps that are described below:-

1. Declaration and initialization:- Firstly you need to declare and initialize your array with whatever similar data type you want to take. In this example, we will be taking an array of integers. Here n is the size of an array.

int arr[]={1,2,3,4,5,6,7};
int n=7;

2. Taking value as input:- The next step is to take the value from the user that he/she want to search in our array. This can be done by simply using a cin statement.

int val;
cout<<"Enter the value you want to search"<<endl;
cin>>val;

3. Function:- Here comes the most important step. we will make a function named searchvalue of type void. In addition to this, we are taking our array, the size of the array, and the value that we want to search as function arguments.

Inside this function, we will loop through the array elements and linearly search for our respective value.

if we find our value then we will print the index at which our value is present. Here I am using i+1  just to avoid confusion as I already told you that array index starts from zero. by writing i+1 it will make our index start with one.

if in case we traverse the whole array but don’t find our desired value then we will exit through the loop and execute the statement outside the loop (i.e. value does not exist).

void searchvalue(int arr[],int size,int value)
{

     for(int i=0;i<size;i++)
     {
         if(arr[i]==value)
         {
            cout<<"value present at index no:"<<i+1<<endl;
            return;
         }

     }
     cout<<"value do not exist"<<endl;

}

 

4. Function Call:- Lastly we will call our function inside the main function.

searchvalue(arr,n,val);

 

Entire code

#include <iostream>
using namespace std;


void searchvalue(int arr[],int size,int value)
{

     for(int i=0;i<size;i++)
     {
         if(arr[i]==value)
         {
            cout<<"value present at index no:"<<i+1<<endl;
            return;
         }

     }
     cout<<"value do not exist"<<endl;

}

int main()
{
    int arr[]={1,2,3,4,5,6,7};

    int n=7;

    int val;
    cout<<"Enter the value you want to search"<<endl;
    cin>>val;

    searchvalue(arr,n,val);

    return 0;
}

Here the time complexity is O(n).

 

That’s it for this tutorial.

Thank You!

Leave a Reply

Your email address will not be published.