Array-promo

Question

print largestĀ  and smallest element in an unsorted array.

Share code with your friends

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

Code

				
					import java.util.Scanner;
public class largestAndSmallestElementInAnUnsortedArray
{  
    public static void main(String[] args)
    {  
        /* Initialize array */  
        int [] arr1;
        
        int n=0,i=0,j=0,temp=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] + " ");  
        }  
          
        /* 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();  
          
        System.out.println("Largest Elements of array: "+arr1[0]);  
        System.out.println("Smallest Elements of array: "+arr1[(n-1)]);  
        
    }  
}    
				
			

Coding Store

10-minute Stress-Buster Games

Leave a Reply

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