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

From CompSciWiki
Jump to: navigation, search
m (Fixed photo)
(Fixed sidebar title)
Line 68: Line 68:
 
</pre>
 
</pre>
  
|SideSectionTitle=...by students
+
|SideSectionTitle=Array Algorithms
  
 
|SideSection=
 
|SideSection=

Revision as of 00:16, 9 April 2010

Back to the Program-A-Day homepage

Problem

Consider the provided main method which provides an array of random integers, and an integer value x. Write a method which counts number of times the value x occcurs in the array.

public static void main(String [] args)
    {
        int [] array = {1,2,3,3,4,5,6,7};  // the array to search
        int x = 3;                         // the element we are counting
        int count = 0;                     // number of times x occurs in the array

        // count element x
        count = countElementX (array, x);

        // provide some nice output
        if (count == 0)
            System.out.println("The element " + x + " does not occurs in the array");
        else if (count == 1)
            System.out.println ("The element " + x + " occurs in the array one time");
        else
            System.out.println ("The element " + x + " occurs in the array " + count + " times");

    } // main

The method should accepts an array of integers and an integer value x. The method should perform a linear search of the array. A counter variable 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.

 

Array Algorithms

Wiki array03.jpg


Solution

Create a method to search the array. The method will accept accepts an array of integers and an integer value x. The method will return an integer value indicating the number of times x occurs in the array

private static int countElementX (int [] array, int x)
{
}

Declare 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