This solution is implemented and provided by
=> ITI Dixit
=> Computer Science
=> Banasthali University (Jaipur)
in this class we take size and values of single dimension array from keyboard, then we perform a search operation on the basis of value and index
# save this class inside a file Find.java #
import java.util.*;
public class Find
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER SIZE OF ARRAY : ");
//taking size of array as an input from the user
int size=sc.nextInt();
//array declaration
int[] a=new int[size];
//taking array elements as an input from the user
System.out.println("ENTER ARRAY ELEMENTS : ");
for(int i=0;i<size;i++) {
a[i]=sc.nextInt();
}
//display of array elements using foreach loop
System.out.println("ARRAY ELEMENTS ARE : ");
for(int i : a)
System.out.println(i);
System.out.println("-------------------------------------------------");
//taking user's choice according to the menu
System.out.println("ENTER CHOICE : \n 1. FIND BY VALUE \n 2. FIND BY INDEX");
int ch=sc.nextInt();
switch(ch)
{
case 1:
//taking a number as an input from the user
System.out.println("PLEASE ENTER A NUMBER : ");
int num=sc.nextInt();
//variable for storing first index of the number
int index = 0;
for(int i=0;i<size;i++)
{
if(a[i]==num)
{
index=i;
break;
}
}
System.out.println("FIRST INDEX OF "+num+" = "+index);
break;
case 2:
//taking an index as an input from the user
System.out.println("PLEASE ENTER AN INDEX : ");
int ind=sc.nextInt();
//checking if the index is validate or not
if(ind<0 || ind>size-1) {
System.out.println("INVALID INDEX");
}
else
//display of element at the given index if it is valid
System.out.println("ELEMENT AT INDEX "+ind+" = "+a[ind]);
break;
default:
System.out.println("INVALID CHOICE");
}
}
}
No comments:
Post a Comment