Question #288727

Write a program to create an array in order to store 30 numbers then display the highest number and second highest number present in it using bubble sorting.

The program must be written like-

/*To display the highest number and second highest number*/

import java.util.*;

class Highest

{

public static void main(String args[])

{

Scanner sc = new Scanner(System.in);

int a[]=new int[30];

int i; //To control loop

int j,d; //For using in swapping elements in bubble sorting

int n; //For controlling highest number

System.out.println("Enter 30 numbers");

for(i=0;i<30;i++)

{

a[i] = sc.nextInt();

}

// Stored 30 numbers in an array

for(i=0;i<29;i++)

{

for(j=0;j<29-i;j++)

{

if(a[j] < a[j+1])

{

d = a[j];

a[j] = a[j+1];

a[j+1] = d;

// Elements swapped in descending order

}

}

}

Find the highest and second highest number in the array i.e. a[30]


Expert's answer

/*To display the highest number and second highest number*/
import java.util.*;

class Highest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a[] = new int[30];
        int i; //To control loop
        int j, d; //For using in swapping elements in bubble sorting
        int n; //For controlling highest number
        System.out.println("Enter 30 numbers");
        for (i = 0; i < 30; i++) {
            a[i] = sc.nextInt();
        }
// Stored 30 numbers in an array
        for (i = 0; i < 29; i++) {
            for (j = 0; j < 29 - i; j++) {
                if (a[j] < a[j + 1]) {
                    d = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = d;
// Elements swapped in descending order
                }
            }
        }
        System.out.println(a[0] + " " + a[1]);
    }
}
LATEST TUTORIALS
APPROVED BY CLIENTS