Count Element x Using Linear Search

From CompSciWiki
Revision as of 12:39, 6 April 2010 by BradV (Talk | contribs)

Jump to: navigation, search

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 don't have an array to search 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