Passing Arrays to Functions.pdf - Searching an Array for a Value Since an array stores a set of related values it is often desirable to find out if the

# Passing Arrays to Functions.pdf - Searching an Array for a...

This preview shows page 1 - 3 out of 7 pages.

1 Searching an Array for a Value Since an array stores a set of related values, it is often desirable to find out if the array contains a certain value. When searching for a value, the term key is often used to refer to the value being searched for. For example, suppose we wish to search the marks array for the key 75. This means that we would like to know if the value 75 is stored in the array. The array can be searched by checking each element one by one to see if it is equal to the key. A loop can be used to traverse the array, starting from the first element at location zero. If we come to the last element and the key has not been found, then it can be concluded that the array does not contain the key. The following code is a first attempt at solving the problem. int key; bool found; key = 95; found = false; for (i=0; i<10; i=i+1) { if (marks[i] == key) { found = true; } } if (found == true) cout << "The value " << key << " was found in the array. " << endl; else cout << "The value " << key << " was not found in the array. " << endl; In the code above, if an array element is equal to the key, the Boolean variable, found , is set to true . After the loop terminates, the value of found is checked in an if-then-else statement. If it is true , it means that the key was found. If it is false , it means that the key was not found. In order for this to work, found must be set to false , before entering the loop. Instead of using the Boolean variable found , it is possible to place a cout statement within the if statement to indicate that the key was found: for (i=0; i<10; i=i+1) { if (marks[i] == key) { cout << "The value " << key << " was found in the array. " << endl; } } 2 However, if we do this, it is difficult to indicate that the key was not found. For example, if we put the cout statement that the key was not found after the for loop, it will always display that the key was not found, regardless of what happens inside the loop. If we put the cout statement as part of the if statement within the loop, it will display found or not found for every element in the array. All of these problems are avoided by using the Boolean variable. The code to find out if the array contains the key uses a for loop to traverse the array. Suppose the array contains many elements. As written, even if the key is found early in the array, the entire array has to be traversed, since the for loop goes from the first element to the last. An improvement on this approach is to exit the loop as soon as the key is found (i.e., as soon as  #### You've reached the end of your free preview.

Want to read all 7 pages?

• • •  