Difference between revisions of "Count Element x Using Linear Search"
m (Fixed photo) |
m (Fixed photo) |
||
Line 73: | Line 73: | ||
[[Image:Wiki_array03.jpg|center]] | [[Image:Wiki_array03.jpg|center]] | ||
<BR> | <BR> | ||
− | |||
− | |||
− | |||
− | |||
|Solution= | |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 | 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 |
Revision as of 00:16, 9 April 2010
Back to the Program-A-Day homepage
ProblemConsider 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. |
...by students
| |
---|---|---|
SolutionCreate 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 |