3.4k views
25 votes
java Two smallest numbers Write a program that reads a list of integers, and outputs the two smallest integers in the list, in ascending order. The input begins with an integer indicating the number of integers that follow. You can assume that the list will have at least 2 integers and fewer than 20 integers. Ex: If the input is: 5 10 5 3 21 2 the output is: 2 and 3 To achieve the above, first read the integers into an array. Hint: Make sure to initialize the second smallest and smallest integers properly.

User Josephap
by
5.3k points

1 Answer

4 votes

Answer:

The code to this question can be defined as follows:

import java.util.*;//import package for user input

public class Main //defining a class

{

public static void main(String[] args)//defining main method

{

int m1,m2,num,t,i;//defining integer variable

Scanner incx = new Scanner(System.in);//creating Scanner class object

m1 = incx.nextInt();//input value

m2 = incx.nextInt();//input value

if (m1 > m2)//use if block to check m1 greater than m2

{//swapping value

t = m1;//holding m1 value in t

m1 = m2;//defining m1 that take m2

m2 = t;//holding m2 value

}

for (i = 2; i < 6; i++)//defining for loop

{

num = incx.nextInt();//input value

if (num < m1) //defining if block to smallest value

{

m2 = m1;//holding m2 value in m1

m1 = num;//holding num value in m1

}

else if (num < m2)//defining if block to smallest value

{

m2 = num;//holding num value in m2

}

}

System.out.println(m1 + " " + m2);//print two smallest values

}

}

Output:

5

10

5

3

21

2

2 3

Step-by-step explanation:

In the above code, five integer variable "m1, m2, num, t, and i" is declared, in which it creates the scanner class object for inputs the value and use m1 and m2 use to the input value.

In the next step, if a block is used to swap the value and pass into the for loop that use if block to find the two smallest values and hold its value into the m1 and m2 and print its value.

User Andrej Oskin
by
5.5k points