w3resource

Java: Check if there is a 10 in a given array of integers with a 20 somewhere later in the array


10 Before 20 Check

Write a Java program to check if there is a 10 in an array of integers with a 20 somewhere later on.

Pictorial Presentation:

Java Basic Exercises: Check if there is a 10 in a given array of integers with a 20 somewhere later in the array


Sample Solution:

Java Code:

import java.util.*;

public class Exercise96 {
    public static void main(String[] args) {
        int[] array_nums = {10, 70, 80, 50, 20, 13, 50};
        boolean testd = false; // Initialize a boolean variable for testing
        int result = 0; // Initialize a result variable to track the outcome
        int x = 10; // Define the first number to search for
        int y = 20; // Define the second number to search for

        // Iterate through the array
        for (int i = 0; i < array_nums.length; i++) {
            if (array_nums[i] == x)
                testd = true; // Set the boolean flag when x is found in the array

            // Check if both x and y are found in the array with specific conditions
            if (testd && array_nums[i] == y) {
                System.out.printf(String.valueOf(true)); // Print true when both x and y are found
                result = 1; // Set the result to 1
            }
        }

        // If result is still 0, it means y did not follow x in the array
        if (result == 0) {
            System.out.printf(String.valueOf(false)); // Print false
        }
        System.out.printf("\n"); // Add a newline character for formatting
    }
}

Sample Output:

true

Flowchart:

Flowchart: Java exercises: Check if there is a 10 in a given array of integers with a 20 somewhere later in the array


For more Practice: Solve these Related Problems:

  • Write a Java program to check if an array contains a 5 before any 15.
  • Write a Java program to check if a number X appears before another number Y in an array.
  • Write a Java program to find the first occurrence of 50 in an array and check if 100 appears later.
  • Write a Java program to determine if the sum of numbers before a given number is greater than the sum after it.

Go to:


PREV : Create String Array 0 to N-1.
NEXT : Number Adjacent or Separated by One.


Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.