Monday, 14 March 2016

Check whether a number is present in an array - simple java coding



/*check an number present in an array or not*/

import java.io.*;
class check
{
public static void main (String args[]) throws IOException
{
DataInputStream s = new DataInputStream(System.in);
int n,i,x,flag;
flag=0;
int a[] = new int [100];
System.out.println("Enter the number of elements");

n= Integer.parseInt(s.readLine());
  System.out.println("Enter the "+n+"numbers");
  for(i=0;i<n;i++)
  {
    a[i]=Integer.parseInt(s.readLine());
  }
  System.out.println("Enter the number you want to search");
  x=Integer.parseInt(s.readLine());
  for(i=0;i<n;i++)
  {
    if(a[i]==x)
    {
     flag++;
    }
  }

  if(flag==0)
  {
    System.out.println(x+" IS NOT PRESENT");
  }
  else
  {
    System.out.println(x+ " IS PRESENT FOR " +flag+ " TIMES");
  }

}
}

Save the file with the extension . java and open the command prompt.

C:\Documents and Settings\dcom358>H:



H:\>cd java

H:\Java>path=C:\jdk1.3\bin;

H:\Java>javac check.java
Note: check.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.

H:\Java>java check
Enter the number of elements
5
Enter the 5numbers
100
200
100
300
400
Enter the number you want to search
100
100 IS PRESENT FOR 2 TIMES

H:\Java>java check
Enter the number of elements
5
Enter the 5numbers
2650
2354
5286
2547
26478
Enter the number you want to search
2355
2355 IS NOT PRESENT