Read an Even number

Asked

Viewed 87 times

0

I am again in doubt, now the doubt is related to exercise on Desvio de condicional Simples using only the command IF

After reading an integer value, calculate and display its square only if the read value is even. Otherwise, the programme shall be terminated without presenting.

I am in doubt what will be my IF condition that indicates that the calculation will only be performed if the number given by the user is even!

I declared three variables

  1. The number to be entered
  2. The variable that will present the calculation (in case the number squared)
  3. Variable to indicate that the value is even!

And my second question is : If I must declare a variable to indicate that the value needs to be even... Or if I only state two variables!

  • Use the mod, he will capture the rest of the division, for example: if ( (10 % 2) == 0 ) the expression means: *If the rest of the 10/2 division is equal to 0, then do so. You can also use Math.floorMod

  • If you already have some code to solve the problem, it is important that you ask the question, giving more context and highlighting its difficulty

  • Isac.. I didn’t do the code,!

  • Valdeir...in my case I will use if 10 %2.. since I have not yet seen the Math method!

1 answer

1


You only need two variables.

You can do it like this:

int calculo = numero * numero;
if (calculo % 2 == 0) System.out.println(calculo);
// O operador % retorna o resto da divisão. 0 seria numero par, e 1 impar!
// O if não precisa de estar com chaves por conter apenas uma instrução.

And you can do it with even one variable!

if ((numero * numero) % 2 == 0) System.out.println(numero * numero);

Browser other questions tagged

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