Given the following code, what logic would you need to include to double all odd values stored within the array:

int[] myArray = {1,2,3,13,5,6,7,8,9,17};

for (int i = 0; i < myArray.length; i++) {
//your code goes here
}
NOTE: Your response should be just the missing logic--not the entire problem set.

Respuesta :

Answer:

if (myArray[i] % 2 != 0) {

    myArray[i] *= 2;

    System.out.println(myArray[i]);

}

Explanation:

Insert this into your for loop. Basically what it does is check if the array value at a given index is an odd value. For that I got the mod of number divided by 2 (array % 2) and if the mod is different than zero then the number is "odd".

than I multiplied that value by to, this code:

myArray[i] *= 2;

is the same as doing this:

myArray[i] = myArray[i] * 2;

I have just shortened, but you can do the latter just in case you haven't learned yet.

Anyway, I multiplied by 2 in order to double the values as the question tells.

Then I simply printed these doubled odd values.

But just in case you're not sure, the whole thing goes like this, you can test in your IDE or whatever you are using:

public class Main {

 

public static void main(String[] args) {  

 

 int[] myArray = {1,2,3,13,5,6,7,8,9,17};

 for (int i = 0; i < myArray.length; i++) {

  if (myArray[i] % 2 != 0) {

   myArray[i] = myArray * 2;

   System.out.println(myArray[i]);

  }

 }

}

}

fichoh

To double the odd values in the array, it is essential to first identify the odd values, then multiply each value by 2. Hence, the missing logic is ;

if (myArray[i] % 2 != 0) {

myArray[i] *= 2;

System.out.println(myArray[i]);

}

  • Odd values leaves a remainder when divided by 2 otherwise the value is even ; hence, using the if statement, check if, the value in the array leaves a remainder.

  • If it does, Using, the index value of the value, update the odd value by Multiplying the initial value by 2.

Hence, the missing logic.

Learn more :