Check if a given number exists in an array in C++

In this tutorial, we will learn how to check whether a given number is present in an array in C++.

#include<iostream>
using namespace std;

int main() {
    int array[6]={1,2,3,4,5,6} ;//initializing array
    int target=2;
    bool found;
    for(int i=0;i<6;i++)//using for loop
    {
        if(target == array[i])//using if condition
        {
            found=true;
            cout<<"\n number is present";
            
        }
        
        
    }
    if(found!=true){
            cout<<"\nnumber is not present";
    }
    
}

CODE EXPLANATION

  1. In the above code first, we have taken an array of size 6 and then initialize an integer variable “target” which we will find in the array.
  2. After that we declare bool “found”.
  3. Then we use a for loop that will have total iterations equal to the size of a declared array.
  4. Inside the loop, we used the if condition and when the condition becomes true then statements inside the if condition will run.
  5. Condition is when the “target” variable becomes equal to an array element then set “found” true and displays a message.
  6. So in every iteration of for loop, an element from the array will be compared with the “target” element to check whether the condition is true or not.
  7. At the end, we used another if condition which is when “found” is not set to true the display another message.

OUTPUT

number is present

In code, we take our “target” variable 2  which is present in our declared array therefore we got the message “number is present”.

Leave a Reply

Your email address will not be published.