vendredi 7 septembre 2018

why is the for loop happening 3 times when the if statement is only true twice?

why is my code executing the body inside the for loop 3 times?

should it not only happen 2 times?

why 3 times?

when I run this I get:

"4 divided by 2 the remainder is

0

4 divided by 3 the remainder is

1

4 divided by 4 the remainder is

0

loop has exited out of for loop because D is now 5 count is now 2.

code inside if statement should've happend 2 times

value of N is 4"

public class forIf {

public static void main (String[] args) {

int D;
int N = 4;
int count;

count = 0;

for (D = 2; D <= N; D++) {
  if (N % D == 0)
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
}
System.out.println("loop has exited out of for loop because D is now " + D);
System.out.println("count is now " + count + ". code inside if statement should've happend " + count + " times");
System.out.println("value of N is "+ N);
}
}
// shouldn't the code inside the if statement only happen twice?
// because N % D is only true twice?
// why is it running that block 3 times?

Aucun commentaire:

Enregistrer un commentaire