Because "my program" did not increment the value 5 being that it less than 5.5

1

I'm starting the programming and always try to unravel the things that are not clear, so far I have, but here I tried and tried and could not understand why the program did not increase the value 5 being that less than 5.5

public class Primo {
public static boolean ehPrimo(float nr) {
    if (nr < 2)
        return false;
    for (float i = 2; i <= (nr / 2); i++) {
        if (nr % i == 0)
        return false;
        System.out.println("nr = " + nr + "\ti = " +i);
    }
    return true;
}

public static void main(String[] args) {
    float x = 11f;
    if (ehPrimo(x)) // se for primo
        System.out.println(x + " e primo");
    else // se não for primo
        System.out.println(x + " não e primo");
}
}
    
asked by anonymous 04.06.2016 / 04:40

1 answer

1

Doubt was halfway through the air, but from what I understand you want to know why it has not cycled.

O in your code when we enter the value 11 does the following:

  • Initial value: 2.0 Value when the cycle ends: 3.0
  • Initial value: 3.0 Value when the cycle ends: 4.0
  • Initial value: 4.0 Value when the cycle ends: 5.0
  • Initial value: 5.0 Value when the cycle ends: 6.0

So at the end of the last cycle it is already bigger than 6 so it does not increment again.

for (float i = 2; i <= (numero / 2); i++) { //conteúdo do for... }
  • starts the variable
  • check the condition: i
  • 04.06.2016 / 05:57