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
Taken from http://www.flickr.com/photos/daniello/565304023/
An image or By Students section
|
Solution
The 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
|
Code
Solution Code
public class LinearSearchCountX
{
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
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
|
Back to the Program-A-Day homepage