Metadata

  • πŸ“… Date :: 09-06-2025
  • 🏷️ Tags :: cpp

Notes

Detailed Notes on Searching an Array in C++

In this detailed explanation, we are going to walk through the process of searching for an element in an array using a linear search method in C++. The example given works with both arrays of integers and arrays of strings, demonstrating how to adapt the code to different data types.

Key Concepts

  1. Arrays in C++: An array is a collection of elements, all of the same type, placed in contiguous memory locations. In C++, arrays are zero-indexed, meaning the first element of an array is accessed at index 0, the second at index 1, and so on.
  2. Linear Search: This is one of the simplest search algorithms where you begin at the start of the array and check each element one by one until you find the element you’re searching for or reach the end of the array. In the case of a mismatch, the next element is checked until either a match is found or all elements are exhausted.

Step-by-Step Explanation

1. Creating an Array

In C++, arrays can be defined by specifying the type of elements and the number of elements in the array. Here, we are working with a basic array of integers.

int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 

This creates an array called numbers containing integers from 1 to 10.

2. Calculate the Size of the Array

In C++, the sizeof operator can be used to get the size of an array in bytes. To determine the number of elements in the array, we divide the total size of the array by the size of one element.

int size = sizeof(numbers) / sizeof(numbers[0]);
 

This gives the number of elements in the array. Here, it calculates the size of the numbers array and divides it by the size of one element, which is sizeof(numbers[0]) (the size of an integer).

We will accept user input for the element we want to search for. This is done using cin to input the number.

int mynum;
cout << "Enter element to search: ";
cin >> mynum;
 

4. Search Function Definition

Next, we define a function called search_array that will handle the logic of searching for an element in the array. The function accepts three parameters: the array, its size, and the element we are searching for.

int search_array(int arr[], int size, int element)
 

This function will return the index of the element if found, or -1 if the element is not found.

5. Linear Search Logic

In the search_array function, a for loop is used to iterate over each element in the array and check if the element matches the search query.

for (int i = 0; i < size; i++) {
    if (arr[i] == element) {
        return i;  // Return the index if found
    }
}
return -1;  // Return -1 if element is not found
 
  • We start at index 0 (i = 0).
  • The loop continues as long as i is less than the size of the array.
  • Inside the loop, we check if arr[i] is equal to the element being searched. If we find a match, we return the index i.
  • If the loop finishes without finding the element, we return 1, which indicates that the element is not present in the array.

6. Call the Search Function and Display Results

In the main function, we call the search_array function and pass the numbers array, its size, and the mynum variable to search for the desired element.

int index = search_array(numbers, size, mynum);
 

Then, we check the returned index:

  • If the index is not 1, print the index where the element was found.
  • Otherwise, print that the element is not in the array.
if (index != -1) {
    cout << mynum << " is at index " << index << endl;
} else {
    cout << mynum << " is not in the array." << endl;
}
 

7. Testing the Code

You can test the code by searching for various values and seeing the output. For example:

Enter element to search for: 1
1 is at index 0

If you search for a number that isn’t in the array, the program will return -1.

Enter element to search for: 20
20 is not in the array.


Searching in an Array of Strings

The process of searching through an array of strings is very similar, with a few modifications:

  1. Define the Array of Strings:
string foods[] = {"pizza", "hamburger", "hotdog"};
 
  1. Accept User Input: For strings, use getline() instead of cin to allow the input to contain spaces.
string myfood;
cout << "Enter element to search for: ";
getline(cin, myfood);
 
  1. Modify the search_array Function: The search_array function should now accept an array of strings and the element should be a string as well.
int search_array(string arr[], int size, string element)
 
  1. Test with Strings:

After making the changes, test the code by searching for different food items. The program will display the index of the food if found or print a message saying it’s not in the array.

Example:

Enter element to search for: pizza
pizza is at index 0

Enter element to search for: hamburger
hamburger is at index 1

If you search for something not in the array:

Enter element to search for: sushi
sushi is not in the array.


Conclusion

This process demonstrates how to implement a simple linear search algorithm in C++ to search through an array. Whether you’re working with integers, strings, or other data types, the basic logic of checking each element from the start of the array until a match is found or the array is exhausted remains the same.

Additional Notes:

  • Time Complexity: The time complexity of a linear search is O(n), where n is the number of elements in the array. This means that, in the worst case, you might have to check each element in the array.
  • Alternatives: For larger datasets, more efficient searching algorithms, like binary search, can be used, but this requires the array to be sorted.
  • Array Limitations: In C++, arrays are of fixed size. If the size needs to change dynamically, using data structures like std::vector may be more appropriate.

This example provides a foundation for understanding basic searching in C++, and it can be extended and optimized for more complex use cases.


References