Find the first and second largest number in a series – without using arrays or functions

This is just a revision of my school memories. Language used is Java.





import java.util.Scanner;

public class testmain {
public static void main(String[] args) {

int large = 0; // there is a possible logic error, ignore
int slarge = 0; // there is a possible logic error, ignore

Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements");
int N = scanner.nextInt();

for (int c = 0;c<N;c++) {
int num = scanner.nextInt();

if (num > large) {
large = num;
}

if (num != large && num > slarge) {
slarge = num;
}

}
System.out.println(
"Largest = " + large +
"\nSecond Largest = " + slarge
);
}
}

Leave a Reply