Dremendo Tag Line

Input 10 numbers in 1d array and swap the largest and smallest number in Java

One Dimensional Array - Question 6

In this question, we will see how to input 10 numbers in a one dimensional integer array and interchange the largest number with the smallest number within the array and print the modified array in Java programming. To know more about one dimensional array click on the one dimensional array lesson.

Q6) Write a program in Java to input 10 numbers in a one dimensional integer array and interchange the largest number with the smallest number within the array and print the modified array. Assume that there is only one largest and smallest number.

Single Dimension Array Question 6

Program

import java.util.Scanner;

public class Q6
{
    public static void main(String args[])
    {
        int a[]=new int[10], i,ln=0,lnp=0,sn=0,snp=0;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 10 numbers");
        for(i=0; i<10; i++)
        {
            a[i]=sc.nextInt();
        }

        for(i=0; i<10; i++)
        {
            if(i==0)
            {
                ln=a[i];
                sn=a[i];
                lnp=i;
                snp=i;
            }
            else if(a[i]>ln)
            {
                ln=a[i];
                lnp=i;
            }
            else if(a[i]<sn)
            {
                sn=a[i];
                snp=i;
            }
        }

        a[lnp]=sn;
        a[snp]=ln;

        System.out.println("\nArray after interchanging largest with the smallest");
        for(i=0; i<10; i++)
        {
            System.out.print(a[i]+" ");
        }
    }
}

Output

Enter 10 numbers
18
12
72
10
15
45
38
5
64
11

Array after interchanging largest with the smallest
18 12 5 10 15 45 38 72 64 11
video-poster