Computer Science, asked by aishwaryadcse, 3 months ago

Write a java program to find the index of a specific number k in an unsorted array. If the number is repeated more than once print the index of first
Occurrence of an element​

Answers

Answered by anindyaadhikari13
4

Answer:

The given co‎de is written in Java.

import java.util.*;

public class Index  {

   public static void main(String args[])  {

       Scanner sc=new Scanner(System.in);

       int i,search,n;

       boolean x=true;

       System.out.print("How many elements? ");

       n=sc.nextInt();

       int a[]=new int[n];

       System.out.println("Enter them..");

       for(i=0;i<n;i++)    {

           System.out.print("a["+i+"] = ");

           a[i]=sc.nextInt();

       }

       Arrays.sort(a);

       System.out.println("Sorted Array: "+Arrays.toString(a));

       System.out.print("Enter the element to be searched for: ");

       search=sc.nextInt();

       for(i=0;i<n;i++)    {

           if(a[i]==search)    {

               System.out.println("Position: "+i);

               x=false;

               break;

           }

       }

       if(x)

           System.out.println("Not found in the array.");

       sc.close();

   }

}

See the attachment for output.

Attachments:
Answered by TheUntrustworthy
9

import java.util.";

public class Index {

public static void main(String args[]) {

Scanner sc-new Scanner(System.in);

int i,search,n;

boolean x-true;

System.out.print("How many elements? ");

n=sc.nextInt();

int a[]=new int[n];

System.out.println("Enter them..");

for(i=0;i<n;i++) {

System.out.print("a["+i+"] = ");

a[i]=sc.nextInt();

}

Arrays.sort(a);

System.out.println("Sorted Array: "+Arrays.toString(a));

System.out.print("Enter the element to be

searched for: ");

search=sc.nextInt();

for(i=0;i<n;i++) {

if(a[i]==search) {

System.out.println("Position: "+i);

x=false;

break;

}

}

if(x)

System.out.println("Not found in the

array.");

sc.close();

}

}

Similar questions