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.
5. Complete Program
Answer:
The complete program is given below.
Complete Program
Notice that the two for
statements are the same. This is very common. It would be nice to copy this program to a file and to run it. When you do this, change the length of the array (the 5) to some other value (say, 9) and note the effect.
Review: Recall that the scope of the identifier index
declared in the for
statement is limited to just the body of its loop. So in the program, there are two variables, each named index
, and each limited in scope to the body of its own for
.
import java.util.Scanner ; 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 ( int index=0; index < array.length; index++ ) { System.out.println( "enter an integer: " ); data = scan.nextInt(); array[ index ] = data ; } // write out the data for ( int index=0; index < array.length; index++ ) { System.out.println( "array[ " + index + " ] = " + array[ index ] ); } } } |
Question 5:
The variable
data
is not really needed in this program. Mentally change the program so that this variable is not used.