### Storing multiple information on items: Parallel arrays

• Different properties of the same subject

• Things in the real world usually have many different properties

• Example: some properties of a student

 Student ID: an integer          Name: a string Major: a string Level: an integer (1 = Freshman, 2 = Sophomore, 3 = Junior, 4 = Senior)

• Representing the properties of many different students

• To represent the student ID of a number of students, we can use an array of int

• To represent the name of a number of students, we can use an separate array of String

• To represent the major of a number of students, we can use an separate array of String

• To represent the level of a number of students, we can use an separate array of int

• Furthermore:

• We make certain that:

 The student ID in the ith array element of the student ID array The name in the ith array element of the name array The major in the ith array element of the major array The level in the ith array element of the level array

belong to the same student !!!

• Example: information on 3 students

 314, John Doe, Math, 3 (Junior) 123, Mary Jane, Psych, 1 (Freshman) 876, Peter Pan, Chem, 2 (Sophomore)

stored in 4 arrays as follows:

 studID[0] = 314 name[0] = "John Doe" major[0] = "Math" level[0] = 3 studID[1] = 123 name[1] = "Mary Jane" major[1] = "Psych" level[1] = 1 studID[2] = 876 name[2] = "Peter Pan" major[2] = "Chem" level[2] = 2

Multiple arrays where the elements are "synchronized" to represent information of the same item are called:

 Parallel arrays

• Parallel arrays

• In computing, a parallel array is a data structure for representing arrays of records.

Values located at the same index in each array are implicitly the fields of the same record.

• Example: using parallel arrays to represent student information

 public class ParallelArray1 { public static void main(String[] args) { int[] studID = {314, 123, 876}; String[] name = {"John Doe", "Mary Jane", "Peter Pan"}; String[] major = {"Math", "Psych", "Chem"}; int[] level = {3, 1, 2}; /* ---------------------------------------------- Print the information in the parallel arrays ---------------------------------------------- */ for ( int i = 0; i < studID.length; i++ ) { System.out.print( studID[i] + "\t"); // \t = tab character System.out.print( name[i] + "\t"); System.out.print( major[i] + "\t"); System.out.print( level[i] ); System.out.println(); } } }

• Example Program: (Demo above code)

How to run the program:

 Right click on link and save in a scratch directory To compile:   javac ParallelArray1.java To run:          java ParallelArray1

• Comment

• Parallel arrays is not commonly used in modern programming languages

• Today, we use array of user-defined type (class) instead of parallel arrays

• We will study user-defined types (classes) soon.