Write a function check_all_equal(int[ ] array) that: Takes as input array of int
ID: 3704753 • Letter: W
Question
Write a function check_all_equal(int[ ] array) that:
Takes as input array of integers. The array can have any length.
If the array length is 0, the function returns Boolean value true.
If the array length is not 0:
u? The function returns true if all values in the array are equal to each other.
u? The function returns false otherwise. For example:
If a1 = {20, 20, 20, 20, 20}, then check_all_equal(a1) returns true, since all values equal 20.
If a1 = {1, 1, 1, 2}, then check_all_equal(a1) returns false, since not all values are equal to each other.
If a1 = { }, then check_all_equal(a1) returns true, because the array is empty.
Explanation / Answer
class Main {
// TAKING an array as an argument
static boolean check_all_equal(int[] array)
{
int i;
for(i=0; i<array.length-1; i++)
{
// if any of the two elements are not equal, returning false
if(array[i] != array[i+1])
return false;
}
// if all are same, comes here to return true
return true;
}
public static void main(String[] args) {
System.out.println(check_all_equal(new int[]{20, 20, 20, 20, 20}));
System.out.println(check_all_equal(new int[]{1, 1, 1, 2}));
}
}
/*SAMPLE OUTPUT
true
false
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.