Numbers greater than Given Number From Array in Java

Program description:- Write a Java program to find the numbers which are greater than the given number from an array. Take an array and a number, compare the number with each element of the array.

Example1:-
Array = {10, 20, 30, 40, 50}
Number = 30
Numbers greater than given number = 40, 50

Example2:-
Array = {-10, 5, 0, -9, 18, 27, -36}
Number = 5
Numbers greater than given number = 18, 27

Prerequisite:- Array in Java, find length of array in Java

In this program, we will take input value for the array from the end-user, but you can take it explicitly. See:- how to take array input in Java. We will use a method to perform the operation. 

Procedure to develop Java method to find the numbers greater than the given number,
a) Take an array and a number.
b) Traverse through the array.
c) If the element is greater than the given number then display it.

Java Program to Find Numbers Greater than Given Numbers From Array

import java.util.Scanner;

public class ArrayTest {

  public static void main(String[] args) {
    // create Scanner class object to take input
    Scanner scan = new Scanner(System.in);

    // read size of the array
    System.out.print("Enter size of the array: ");
    int n = scan.nextInt();

    // create an int array of size N
    int numbers[] = new int[n];

    // take input for the array
    System.out.println("Enter array elements: ");
    for (int i = 0; i < n; ++i) {
      numbers[i] = scan.nextInt();
    }

    // take number
    System.out.print("Enter number = ");
    int num = scan.nextInt();
    
    // display numbers greater then given number
    System.out.println("Numbers greater then given number = ");
    display(numbers, num);

    // close Scanner
    scan.close();
  }

  // method to display numbers greater than given number
  public static void display(int[] numbers, int num) {
    // traverse through the array
    for (int i : numbers) {
      if(i > num)
      System.out.print(i+" ");
    }
    
  }
}

Output:-

Enter the size of the array: 5
Enter array elements:
10 20 30 40 50
Enter number = 30
Numbers greater than given number =
40 50

Enter the size of the array: 7
Enter array elements:
-10 5 0 -9 18 27 -36
Enter number = 5
Numbers greater than given number =
18 27

Also See:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *