OneBite.Dev - Coding blog in a bite size

Search For A Specific Element In An Array In C++

Code snippet for how to Search For A Specific Element In An Array In C++ with sample and detail explanation

Searching for a specific element in an array is a common task in programming. In this article, we will focus on how to accomplish this in C++ using straightforward steps and explanations.

Code Snippet: Finding a Specific Element in a C++ Array

Here we represent a simple C++ program that looks for a specific element in an array.

#include<iostream>
using namespace std;

int main() {
    int array[5] = {10, 20, 30, 40, 50};
    int searchElement = 30, i;

    for(i = 0; i < 5; i++) {
        if(array[i] == searchElement) {
            cout << "Element found at index: " << i << endl;
            break;
        }
    }

    if(i == 5) {
        cout << "Element not found in the array." << endl;
    }

    return 0;
}

Running the above C++ code will result in the output: "Element found at index: 2"

Code Explanation for Finding a Specific Element in a C++ Array

This is a very basic and beginner-friendly search operation in a C++ array, explained step-by-step.

  1. Header Files: Firstly, the C++ code example includes the <iostream> header file which provides basic input/output operations. The using namespace std; line eliminates the need to write std:: before any standard functions.
#include<iostream>
using namespace std;
  1. Main Function: In the main function of our program, an integer array of size 5 is initialized with values from 10 to 50 incrementing by 10. We have defined the element ‘30’ as the one to search for in the array.
int array[5] = {10, 20, 30, 40, 50};
int searchElement = 30, i;
  1. Traverse and Search: Next, we traverse through the array using a for loop. For each array element, we check if it matches the searchElement. If a match is found, a message is printed to the console with the index position of the found element, and then we break out of the loop.
for(i = 0; i < 5; i++) {
    if(array[i] == searchElement) {
        cout << "Element found at index: " << i << endl;
        break;
    }
}
  1. Element Not Found: If no matching element is found after traversing the entire array, a message indicating that the element was not found is printed out.
if(i == 5) {
    cout << "Element not found in the array." << endl;
}
  1. Exit: Finally, the main function of our C++ program returns 0, which is a way of indicating the successful execution of the program.

Through this simple C++ program, we can locate a specific element within an array. Note that this method only works for arrays where the size and elements are known. Therefore, for larger, dynamic arrays or for more complex searching scenarios, other methods may be preferred.

c-plus-plus