Difference between revisions of "Count Element x Using Linear Search"
From CompSciWiki
Line 5: | Line 5: | ||
|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. | |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. | ||
− | |SolutionCode=<pre>public class | + | |SolutionCode=<pre> |
+ | public class LinearSearchCountX | ||
{ | { | ||
− | }</pre> | + | |
+ | public static void main(String [] args) | ||
+ | { | ||
+ | int [] array = {1,2,3,3,4,5,6,7}; | ||
+ | int x = 3; | ||
+ | int count = 0; | ||
+ | |||
+ | |||
+ | // 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 | ||
+ | |||
+ | private static int countElementX (int [] array, int x) | ||
+ | { | ||
+ | int count = 0; // count the number of times x occurs | ||
+ | int i; // iterate through the array | ||
+ | |||
+ | // check for null before trying to iterate through it | ||
+ | if (array != null) | ||
+ | { | ||
+ | // iterate through all the elements in the array | ||
+ | for (i = 0; i < array.length; i++) | ||
+ | { | ||
+ | // compare the current element with x | ||
+ | if (array [i] == x) | ||
+ | { | ||
+ | // increment the count | ||
+ | ++count; | ||
+ | } // if | ||
+ | } // for | ||
+ | } // if | ||
+ | |||
+ | return count; | ||
+ | } // countElement | ||
+ | } // Arrays | ||
+ | </pre> | ||
|SideSectionTitle=...by students | |SideSectionTitle=...by students |
Revision as of 12:20, 6 April 2010
Back to the Program-A-Day homepage
ProblemWrite 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
An image or By Students section | |
---|---|---|
SolutionThe solution... // some code here | ||
Code |