Question: You dont have to loop through all of the elements of an array. You can loop through just some of the elements of an array
You dont have to loop through all of the elements of an array. You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (&&) on line 14 to make sure that the loop doesnt go beyond the length of the array, because if you had an array that had less than 5 elements, you wouldnt want the code to try to double the 5th element which doesnt exist! Notice that in this code, the array is a private instance variable of the class ArrayWorker. It is created in the constructor and changed or accessed by the methods.
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.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
