Difference between revisions of "Count Element x Using Linear Search"

From CompSciWiki
Jump to: navigation, search
Line 69: Line 69:
 
</pre>
 
</pre>
  
Before trying to iterate through the array, make sure it is properly initialized.  If the array is null, we don't have an array to search so we will return 0.
+
Before trying to iterate through the array, make sure it is properly initialized.  If the array is null, we cannot search the array, so we will return 0.
 
<pre>
 
<pre>
 
if (array != null)
 
if (array != null)

Revision as of 12:41, 6 April 2010

Back to the Program-A-Day homepage

Problem

Write a method which accepts an array of integers and an integer value x. The method will perform a linear search of the array. A counter should be incremented each time the value x occurs in the array. The method should return an integer value indicating the number of times the value x occurs in the array.

 

...by students

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

Initialize the variables we will need. We will need an integer to count the number of times x occurs in the array, and an integer to iterate through the array.

int count = 0;
int i;

Before trying to iterate through the array, make sure it is properly initialized. If the array is null, we cannot search the array, so we will return 0.

if (array != null)

Iterate through each element of the array. On each iteration, compare the current element with the value of x. If the values are equal, increment the counter variable.

for (i = 0; i < array.length; i++){
    if (array [i] == x)
        ++counter;
} // for

Return the number of times element x occured in the array.

return count;

Code

Solution Code

Back to the Program-A-Day homepage