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.
4. Reading in Each Element
Answer:
for ( int index= egArray.length-1 ; index >= 0 ; index-- )I win! You forgot the -1. Off-by-one errors of this kind are very common. It was an easy bet.
Reading in Each Element
Here is a program that prompts the user for each element of an array and reads it in. The array is hard coded to be five elements long. After it is filled with data, the array is written to the monitor.
Usually a program would do something with the data (besides just print it out) after it was read in. This would usually involve more loops.
import java.util.Scanner ; public class InputArray { public static void main ( String[] args ) { int[] array = new int[5]; int data; Scanner scan = new Scanner( System.in ); // input the data for ( ; ; ) { System.out.println( "enter an integer: " ); data = scan.nextInt(); array[ index ] = data ; } // write out the data for ( ; ; ) { System.out.println( "array[ " + index + " ] = " + array[ index ] ); } } } |
Question 4:
Fill in the blanks so that the program works as described. You may wish to copy and paste some of the following phrases. (Hint: you will need to use most phrases twice.)
int index index < = 0 index++ array.length