Run the code below and see if it helps you understand :)
public class Programa {
public static void main(String args[]){
int a = 10;
for (int i = 1; i<=2; i++){
for(int j=0; j<=2; j++){
System.out.println("\nCom i = " + i + " e j = " + j + ", temos: ");
System.out.println("O valor de a, antes do IF/ELSE, é " + a);
if((i%2 == 0) && (j % 2 == 0)) {
a = a * 2;
System.out.println("O valor agora depois do IF é " + a);
} else {
a = a + 1;
System.out.println("O valor agora depois do ELSE é " + a);
}
}
}
System.out.println("O valor de a ao final é " + a);
}
}
Exit from the program:
Com i = 1 e j = 0, temos:
O valor de a, antes do IF/ELSE, é 10
O valor agora depois do ELSE é 11
Com i = 1 e j = 1, temos:
O valor de a, antes do IF/ELSE, é 11
O valor agora depois do ELSE é 12
Com i = 1 e j = 2, temos:
O valor de a, antes do IF/ELSE, é 12
O valor agora depois do ELSE é 13
Com i = 2 e j = 0, temos:
O valor de a, antes do IF/ELSE, é 13
O valor agora depois do IF é 26
Com i = 2 e j = 1, temos:
O valor de a, antes do IF/ELSE, é 26
O valor agora depois do ELSE é 27
Com i = 2 e j = 2, temos:
O valor de a, antes do IF/ELSE, é 27
O valor agora depois do IF é 54
O valor de a ao final é 54
What exactly don’t you understand? You know what the operator
%does? You know how thefor?– Dherik
So I know that the operator % gets the rest of the division. I know that in the example of i, it starts in 1, ends in 2 and adds 1 for each time it adds up. However I cannot understand how it arrived in 54 :/
– GGirotto
Have you tried a table test of the algorithm? It may be useful also, to understand the sequence of the execution of the program, to print the variable
awithinifandelsewhen executing the code.– Dherik
i printed the variable '-' gave 54 rsrs to trying to understand how it arrived at this value...
– GGirotto
Print inside the
ifandelse! Will help you.– Dherik