Would it be possible to identify 2 larger numbers in a sequence of 5 numbers entered by the user?

2

I tried to do it, I researched it, but I could not. I would like to know if it is possible to identify two larger numbers without using vectors ?

Here's my attempt:

int maior1 = 0, 
maior2 = 0;
for(int i = 0; i < 5; i++){
    System.out.println(" Digite números:");
    int num = sc.nextInt();
    if(num > maior1){
        maior1 = num;       
        if(num > maior2){
        maior2 = num;
        }
    }
}

System.out.println(maior1 + "- " + maior2);
}
    
asked by anonymous 01.02.2016 / 02:05

1 answer

5

I think this is enough:

int maior1 = 0, 
    maior2 = 0;
for(int i = 0; i < 5; i++) {
    System.out.println(" Digite números:");
    int num = sc.nextInt();
    if(num > maior1) {
        maior2 = maior1;
        maior1 = num;
    } else if(num > maior2) {
        maior2 = num;
    }
}

System.out.println(maior1 + " - " + maior2);

See working at IDEONE .

The key differences to the original code are:

  • If the number entered is higher than the first one, the first one goes to the second place ( maior2 = maior1; ).

  • We use else to test if the number is the second only if it is not already the first one.

    The else only works if the first if is not executed, after all, if the number is the first, we have already queued the floor: the "ex-first" is moved to the second place, and the number entrant takes the lead, so we do not need to re-test with second place.

01.02.2016 / 02:25