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

Asked

Viewed 74 times

2

I tried to do, I researched about it, but I could not. I wonder if it is possible to identify two larger numbers without the use of vectors?

Follow 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);
}

1 answer

5


I think that’s 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 on IDEONE.

The essential differences for the original code are:

  • if the number entered is greater than the first placed, the first placed goes to the second place (maior2 = maior1;).

  • we use the else to test if the number is the second placed only if he is no longer the first placed.

    The else only works if the first if is not executed, after all, if the number is the first, we have already made the queue walk: the "former first" is moved to the second place, and the number entered takes the lead, so we do not need to make new test with the second placed.

  • 2

    Thank you. I get it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.