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?
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.
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; } } .... }
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With