Java Program to print all the numbers which are less than given key element from a given array.

Get an element and print the elements of array which is less than the element.

Sample Input 1:

5 5 7 9 3 1 4

Sample Output 1:

3 1

Sample Input 2:

5 5 7 9 3 1 8

Sample Output 2:

5 7 3 1

Program or Solution

				
			
					
import java.util.*;
class LessEle
{
  public static void main(String args[])
  {
     int size,i,num,j=0;
     Scanner sc=new Scanner(System.in);
     System.out.println("Enter Size Of Array:");
     size=sc.nextInt();
     int a[]=new int[size];
     System.out.println("Enter The Array Elements:");
     for(i=0;i<size;i++)
        {
            a[i]=sc.nextInt();

	}
     System.out.println("Enter The Number:");
     num=sc.nextInt();
     System.out.println("The Array Elements Less Than That Of Number Is:");     
     for(i=0;i<size;i++)
        {
            if(a[i]<num)
              {
			j++;
                System.out.print(" "+a[i]);
              }
        }
     if(j==0)
        {
           System.out.println("Zero.");
        }
                
  }
}




			
				
			

Program Explanation

Array is a Collection of data with same type.

1. Get the size of the Array

2. Create a array with the given size (Array has 0 to size-1 index to access every location)









        0                        1                        2                         3              ......             size-2                  size-1


3. Get Inputs for Array (See Previous Problems for detail)


In the second for loop 

if(a[i]<num) checks whether element in the location less than num

if the value located in a postion is lesser than the element given by user, then print the value using system.out.println statement.