Array-promo

Question

Write a program to k th largest element in an array.

				
					Input:
ENTER THE SIZE OF ARRAY:10
ENTER THE ELEMENT IN THE ARRAY:
1 2 3 4 5 6 7 8 9 10 

ARRAY AFTER DELETING EVEN POSITION ELEMENTS:
2 4 6 8 10
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner; 
public class kthLargestElementInAnArray 
{   
    public static void main(String[] args)
    {  
        /* Initialize array */  
        int [] arr1;
        
        int n=0,i=0,j=0,temp=0,k=0;
        Scanner sc = new Scanner(System.in);    
        
        System.out.println("Enter a no. of elements in the array");   
        n = sc.nextInt(); 
        System.out.println("Enter numbers in array");
        arr1=new int[n];
        for(i=0;i< n;i++)
        {
            arr1[i]=sc.nextInt();
        }
        System.out.println("Elements of original array: ");  
        for ( i = 0; i < n; i++)
        {   
            System.out.print(arr1[i] + " ");  
        }  
        System.out.println("Enter k th position.(position should be between 0 and "+n+")");
        k=sc.nextInt();
        /* sorting of array in descending order is done here */  
        for (i = 0; i < n; i++) 
        {   
            for ( j = i+1; j < n; j++)
            {   
                if(arr1[i] < arr1[j]) 
                {  
                    temp = arr1[i];  
                    arr1[i] = arr1[j];  
                    arr1[j] = temp;  
                }   
            }   
        }  
        
        System.out.println();  
          
        /* k th element  */  
        if(k>0 && k< n)
        {
            System.out.println(k+" largest element of the given  array is: "+arr1[k]);  
        }
        else
        {
            System.out.println("invalid value of k");
        
        }
    }  
} 
				
			

Coding Store

10-minute Stress-Buster Games

Leave a Reply

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