Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find two smallest numbers using java?

Tags:

java

I need help to compute the two smallest numbers in java?... plzz help.. Usage for arraylist and arrays are not allowed.. The user shall be asked for a terminating value first and will continue to provide inputs and once the user enters the same terminating value the program should output the two smallest numbers from the inputs excluding the terminating value..

Additional Details Could show me how to do it... The sentinel value is the value if entered again by the user shall stop the program and output the two smallest numbers.

package hw4;


public class s1 {

    public static void main(String[] args) {

        int input;
        int min;
        int min2;



        System.out.print("Enter a value to act as sentinel:");
        int sentinel = IO.readInt();

        System.out.println("Enter numbers");
        input = IO.readInt();

        do {

            min = input;
            min2 = input;

            if (input < min) {

                min = input;

            }



            input = IO.readInt();

        } while (input != sentinel);

        // Return the results
        System.out.println("The smallest Number is: " + min);
        System.out.println("The second smallest Number is: " + min2);
    }
}
like image 956
Karan Singh Avatar asked Feb 26 '23 01:02

Karan Singh


2 Answers

I'm assuming this is homework, based on the nature of the question. So ...

Hint: if x was the smallest and y is now the smallest, then x is now the second smallest.

Hint 2: make sure your program works when the smallest and second smallest values are equal.

like image 53
Stephen C Avatar answered Mar 11 '23 07:03

Stephen C


When you find a new min, save the previous minimum in your min2 variable and then reassign min to the current input.

   if (input < min) {
        min2 = min
        min = input;

    }
like image 40
sahhhm Avatar answered Mar 11 '23 07:03

sahhhm