QUESTION #2 (SELF-CHECK)
SOLUTIONS
Note: Each
of these problems can be solved in many ways. It is fine if your solution is different
than the one below.
//2A
public class Question2A
{
public static void main(String[] args)
{
int[] arr = {4, 5,
9, 4, 0, 6, 4, 3};
System.out.println(count(arr, 4)); //outputs
3
}
public static int count(int[] a, int value)
{
int count = 0;
for (int i = 0; i < a.length; i++)
{
if (a[i] == value)
{
count++;
}
}
return count;
}
}
//2B
public class Question2B
{
public static void main(String[] args)
{
int[] numbers = {4, 5, 9, 4, 0, 6,
4, 3};
System.out.println(contains(numbers, 1));
//outputs
false
System.out.println(contains(numbers, 5));
//outputs true
}
public static boolean contains(int[] ar, int value)
{
for (int i = 0; i < ar.length; i++)
{
if (ar[i] == value)
{
return true;
}
}
return false;
}
}
NOTE: Another solution could have been to
call your count function from 2A inside the contains function. Simply if the count function returns 0,
then the array doesn’t contain the value.
Otherwise, it does.
//2C
public class Question2C
{
public static void main(String[] args)
{
int[] data = {4, 5, 9, 4, 0, 6, 4, 3};
System.out.println(findLast(data, 4)); //outputs 6
System.out.println(findLast(data, 0)); //outputs 4
}
public static int findLast(int[] ar, int value)
{
for (int i = ar.length - 1; i >= 0; i--)
{
if (ar[i] == value)
{
return i;
}
}
return -1; //no occurrence found
}
}
//2D
public class Question2D
{
public static void main(String[] args)
{
int[] stats = {4, 5, 9, 4, 0, 6, 4, 3};
System.out.println(max(stats)); //outputs 9
}
public static int max(int[] arr)
{
int max = arr[0];
for (int i=0; i<arr.length; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
return max;
}
}
|