Java: Test that a given array of integers of length 2 contains a 4 or a 7
Contains 4 or 7
Write a Java program to test that a given array of integers of length 2 contains a 4 or a 7.
Sample Solution:
Java Code:
import java.util.Arrays;
public class Exercise78 {
public static void main(String[] args) {
// Define an integer array, array_nums
int[] array_nums = {5, 7};
// Print the elements of the original array
System.out.println("Original Array: " + Arrays.toString(array_nums));
// Check if the first element of the array is 4 or 7 and print the result
if (array_nums[0] == 4 || array_nums[0] == 7) {
System.out.println("True");
} else {
// If the first element is not 4 or 7, check the second element and print the result
System.out.println(array_nums[1] == 4 || array_nums[1] == 7);
}
}
}
Sample Output:
Original Array: [5, 7] true
Pictorial Presentation:
Flowchart:
For more Practice: Solve these Related Problems:
- Modify the program to check if the array contains 3 or 9 instead.
- Write a program to check if an array contains only prime numbers.
- Modify the program to count how many times 4 or 7 appear in the array.
- Write a program to check if all elements in an array are either 4 or 7.
Go to:
PREV : New Array with Ends of Two Arrays.
NEXT :
Rotate Array Left.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.