This book is now obsolete Please use CSAwesome instead.

8.5. Looping through Part of an Array

You don’t 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 12 to make sure that the loop doesn’t go beyond the bounds of the array.

You can even start in the middle and loop through the rest of the array. Does this work for arrays that have an even number of elements? Does it work for arrays that have an odd number of elements? Modify the main code below to test with both arrays with an even number of items and an odd number.

Mixed up programs

The following program has the correct code to reverse the elements in an array, a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.</p>

The following program has the correct code to return the average of the first 3 items in the array a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.</p>

You have attempted of activities on this page