Java Program to exchange the smallest and largest number in an array of N integers.

import java.util.Scanner;

public class Program 
{   
    	public static void main( String[] args ) 
    	{
			Scanner reader = new Scanner(System.in);
			int maximum, min, size, c, i=0, j=0;

			System.out.print("\nEnter the number of elements in array : ");
			size = reader.nextInt();
			int[] array = new int[size], location1 = new int[size], location2 = new int[size];
			System.out.print("\nEnter "+ size +" integers\n");
			for (c = 0; c < size; c++)
				array[c] = reader.nextInt();
			maximum = array[0];
			min = array[0];
			for (c = 1; c < size; c++)
			{
				if (array[c] > maximum)
				{
					maximum = array[c];
				}
				if (array[c] < min)
				{
					min = array[c];
				}
			}
			for(c = 0; c < size; c++)
			{
				if(array[c] == maximum)
				{
					location1[i] = c + 1;
					i++;
				}
				if(array[c] == min)
				{
					location2[j] = c + 1;
					j++;
				}
			}
			System.out.print("\nBiggest element is present at location ");
			if(i==0)
				System.out.print( 1 );
			else
			{
				for(c=0; c<i; c++)
				{
					if(c>0)
						System.out.print(", ");
					System.out.print(location1[c]);
				}
			}
			System.out.print(" and it's value is " + maximum);
	
			System.out.print("\nSmallest element is present at location ");
			if(j==0)
				System.out.print( 1 );
			else
			{
				for(c=0; c<j; c++)
				{
					if(c>0)
						System.out.print(", ");
					System.out.print(location2[c]);
				}
			}
			System.out.print(" and it's value is " + min);
		
			System.out.print("\nArray after interchange of smallest and largest :");

			for(c = 0; c < size; c++)
			{
				if(array[c] == maximum)
				{
					array[c] = min;
					continue;
				}
				if(array[c] == min)
				{
					array[c] = maximum;
				}
			}
			for(c = 0; c < size; c++)
			{
				System.out.print("\n"+ array[c]);
			}
    	}
}

Output :
Enter the num of elements : 5
Enter the elements :
10
20
30
40
50

Biggest element is 50 and Smallest elementis 10

Array after interchange of smallest and largest :

Element : 50
Element : 20
Element : 30
Element : 40
Element : 10



Leave a comment