Common Array Algorithms
This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.
2. Counting Loops and Arrays
Answer:
This sounds like a good place for a counting loop.
Counting Loops and Arrays
public class CountArray { public static void main ( String[] args ) { int[] egArray = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 }; for ( int index = ; ; ) { System.out.println( ); } } } |
In Java, the index of an array starts at 0 and counts up to one less than the number of elements in the array. Counting loops can easily do that. The example program (above) does that, except for a blank or two.
The variable egArray
refers to an array object that has been constructed using an initializer list.
Question 2:
Fill in the blanks so that the program prints out every element, in order. You may wish to copy and paste from the following:
0
index++
egArray[index]
index < 10
(Highlight a string and then use use "copy" and "paste" commands from the "edit" menu of your browser to paste the string into a blank. Or use control-c and control-v as shortcuts for copy and paste.)