N
N
nedevochka2022-03-15 19:57:06
Java
nedevochka, 2022-03-15 19:57:06

Why does the for loop work despite false?

public class JavaApplication33 {

    public static void main(String[] args) {
        int i, j;
        boolean b;
        
        for( i = 2;  i < 100;  i++) {
            b = true;
            
            //проверить, делится ли число без остатка
            for ( j = 2;  j <= i / j   ; j++)
                
                //если число делится без остатка, значит, оно не простое
                if( ( i % j ) ==  0 ) b = false;
            
            if (b)
                System.out.println( i + " - простое число" );
        }
    }
    
}

I'm learning java, the solution is copied from Schildt's textbook, questions about the second cycle
Let's say the number i = 7, and j = 3, the for loop according to the conditions ( j <= i / j ) must be false (because 3 <= 7/ 3 is logically wrong), but j still continues to increase according to the iteration, although the loop should have stopped executing, why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rPman, 2022-03-16
@rPman

because the assignment b=false itself does not cancel the loop, you need to do a break

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question