148k views
5 votes
What will the following code print out? Can you write a similar method called tripleFirstFour() that triples the first 4 elements of the array? Make sure you test it in main.public class ArrayWorker{/** Doubles the first 5 elements of the array */public static void doubleFirstFive(int[] values){// Notice: && i < 5for (int i = 0; i < values.length && i < 5; i++){values[i] = values[i] * 2;}}/** Write a method called tripleFirstFour() that triples the first 4 elements of the array **/public static void printArray(int[] values){for (int i = 0; i < values.length; i++){System.out.println( values[i] );}}public static void main(String[] args){int[] numArray = {3, 8, -3, 2, 20, 5, 33, 1};doubleFirstFive(numArray);printArray(numArray);}}

User Vijay S
by
8.0k points

1 Answer

6 votes

The code will print out the elements of the array "numArray" after they have been doubled by the "doubleFirstFive" method. The "doubleFirstFive" method takes in an array as a parameter and uses a for loop to double the value of the first 5 elements of the array, using the "&& i < 5" condition in the for loop to ensure that only the first 5 elements are doubled.

A similar method called "tripleFirstFour" that triples the first 4 elements of the array can be written as follows:

----------------------------------------------------------------------------

// Notice: && i < 4

for (int i = 0; i < values.length && i < 4; i++){

values[i] = values[i] * 3;

}

}

------------------------------------------------------------------

To test the method, you can add the following code in the main method:

-------------------------------------------------------------

tripleFirstFour(numArray);

printArray(numArray);

-------------------------------------------------------------

This will call the "tripleFirstFour" method on the numArray and then print the new array out on the console.

User Site
by
8.5k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.