Program to search an element in the array

Program to search an element in the array in C++

Program to search an element

In this we will be discussing to find whether an element is present in an array or not, with the user input of number of elements and the elements in the array.

Write a C program to input elements in array and search whether an element exists in array or not. Also, to print the index at which it is found.

Sample input:

6 100

20 25 100 95 45 5

Sample output:

100 is present in the array

The element is present at index : 2

Program to search an element in the array

Logic and procedure to follow to get the required results

1. Declare the required variables to use

2. Input the size, search element, and arrays element by the users end.

3. Declare and assigned a variable to zero, assuming that the element does not exist in the array.

                    i.e., flag = 0

4. Apply the required looping from initialization till the required size

                   i.e., for( int i=0; i<n; i++ )

5. Inside the looping, check if the array element is equal to the search element

                   i.e., if( arr[i] == search_element )

6. If element is found set flag to 1 and end the loop, if not found no need to continue.

7. Also, outside the looping if value of flag is equal to 1 then element found else not found.

                  i.e., if(flag == 1) then “found” else “not present”

👨‍💻Lets proceed to the coding part of the problem

Code :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>

using namespace std;

int main() {

    int n,search_element,flag,index;

    cin>>n>>search_element;

    int arr[n];

    for(int i=0;i<n;i++)

    {


        cin>>arr[i];

    }

    flag=0;

    index=0;

    for(int i=0;i<n;i++)

    {

        if( arr[i] == search_element )

        {

            flag=1;

            index=i;

            break;

        }

    }

    if( flag == 1 )

    {

        cout<<search_element<<" is present in the array\n";

        cout<<"The element is present at position : "<<index;

    }

    else

    {

        cout<<"Element do not found in the array";

    }

    return 0;

}


Output for the test case passed :

If you liked this post, then share this with your friends and if anything is confusing or incorrect then let me know in the comment section.

Thanks form my side, this is Mayank, keep learning and exploring and stay safe !!

Mayank Pathak is the editor and blogger at "The Coding Bro".He loves to codes, learn new technologies, and write the coding solutions and articles for the communities of learners, especiall…

Post a Comment

Please do not enter any spam link in the comments.
© THE CODING BRO. All rights reserved. Premium By The Coding Bro