Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Two largest numbers in a list without using Array

Tags:

java

I'm Stuck with my homework. Basically,we need to Create a program to find the largest and smallest integers in a list entered by the user.And stops when the user enters 0. However we are not allowed to user arrays for this problem.

and one more condition : If the largest value appears more than once, that value should be listed as both the largest and second-largest value, as shown in the following sample run.

I have met the first condition of the program however I cannot meet the 2nd condition.

import java.util.Scanner;
public class FindTwoLargest {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num = 1, max1st = 0, max2nd = 0;
        int count = 1;
        System.out.println("This program allows the user to create a list integers until the user enters 0");
        System.out.println("The program will print the Largest value and the Second largest value from the list!");
        while(num != 0) {
            System.out.print("Integer No." + count + " ");
            num = sc.nextInt();

            if(num >= max1st && num >= max2nd) {
                max1st = num;
            }
            if(num >= max2nd && num < max1st) {
                max2nd = num;
            }
            count++;
        }
        System.out.println("The largest value is " + max1st);
        System.out.println("The second largest value is " + max2nd);

   }
}

I have tried to use this code.

 if(num >= max2nd && num <= max1st) {
max2nd = num;
            }

however when I run the program https://imgur.com/a/YMxj9qm - this shows.

It should print 75 and 45 . What can I do to meet the first condition and meet the second condition?

like image 740
Joshua Salcedo Avatar asked Aug 19 '19 13:08

Joshua Salcedo


People also ask

How do you find the second largest number without an array?

Logic To Find First and Second Biggest Number in N Numbers, without using Arrays. First we ask the user to enter length of numbers list. If user enters limit value as 5, then we ask the user to enter 5 numbers. Once the user enters limit value, we iterate the while loop until limit value is 0.

How do you find the second largest number without an array in Java?

3 Answers. Show activity on this post. int secondLargest = 0; ..... for (..) { .... if (c % 3 == 0) { if (c >= max) { secondLargest = max; max = c; } if (c >= secondLargest && c < max) { secondLargest = c; } } .... }


Video Answer


1 Answers

If you exceed your maximum number (max1st), your new maximum number will be set to num. But your second largest number will be the current maximum number. So try this condition:

if (num > max1st) {
    max2nd = max1st;
    max1st = num;
} else if (num > max2nd) {
    max2nd = num;
}
like image 76
Torsten Fehre Avatar answered Sep 21 '22 00:09

Torsten Fehre