Count Element x Using Linear Search
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 | |
---|---|---|
SolutionInitialize 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 |