Вы находитесь на странице: 1из 18

Arrays I

H. Kandjimi PRG510S
CONTENT OVERVIEW:
 Loops review
 Arrays
 Declaring and Creating Arrays
 Loops to navigate and manipulate Arrays
 Enhanced Loop or For each loop
 Paired Arrays

2
Arrays
 Intro. to data structures - collections of related data items
 Arrays are data structures consisting of related data items of the same
data type stored in consecutive memory locations and has a fixed size.
 Arrays make it convenient to process related groups of values, such as :
• A list of 20 student names, a list of cities in Namibia, ages of students and etc.
 Array Features :
• An array behaves like a numbered list of variables with a uniform naming
mechanism
• It has a part that does not change: the name of the array
• It has a part that can change: the index - an integer in square brackets represents
the positions in an array ( always starts at 0) 3
Loops Review
 Which loop will you use to print your name 15 times? Create a valid java
declaration to accomplish this
 Convert the following Loop, into a do while
for (int i = 0; i < 10; i++) {
System.out.println("Good morning all!!");
}
 What might be the error in the code snippet below:
int count = 0;
while(count <= 0 || true){
System.out.println("This is an interesting loop"); 4

}
Arrays
 We have used arrays when we dealt with CMD arguments
• The list is a collection of strings, args[0], args[1] …args[n]
• args is the array name as declared or passed to the main method
 An array Example ,a list of 20 student names :
• names[0],names[1],names[2] …..names[19]
 Array declaration hints :
• Naming should be in plural, grades, studentAges, scores etc
• Size is fixed must be indicated at declaration
• Data types of all values MUST be the same

5
Array declarations I
 Syntax for declaring an array with new
• data_type[] arrayName = new data_type[size];
• data_type can be any valid types such as Double,Char
• [] indicates that this is an array or data structures
• arrayName is just like a variable name
• The size is a non-negative integer (int, short or long)
 Common way to look/visualize Arrays: double temperature = new double[7];

6
Array declarations II
 Syntax for declaring an array with values
• data_type[] arrayName = {value1,value2,
value3..valueN};
• The left side is just as before
• The size however is not specified, but rather determined by the number
of values
 Examples:
• double temperature = {30.5,25,15.2,20.9,32.3};
• char letters = {'a', 'b', 'c', 'd'};

7
Array declarations: Exercises
 Create valid array declarations for the following:
• To store 10 names of Lecturers
• To store 65 ages of students
• To store the following values:
Windhoek,Harare,Maputo,Lusaka and Gaborone
• To store the following grades: 78, 56.3,96.5,45,
25.6,88,65,48.5
 Share and Comment on your neighbors’s work.
8
Array Indexing
 As indicated early array indices start from 0 up to size-1
 Hence if you had the array below:
String capitalCities =
{“Windhoek”,”Harare”,”Maputo”,”Lusaka”,”Gaborone”};
 Then :
capitalCities[0] => Windhoek
capitalCities[2] => Maputo
capitalCities[4] => Gaborone
 How about capitalCities[5] ??
9
Array Indexing: Array Index Out of Bounds
 Array indices always start with 0, and always end with the
integer that is one less than the size(size -1) of the array.
• The most common programming error made when using arrays is
attempting to use a non-existent array index.
• IndexOutOfBoundsException
 When an index expression evaluates to some value other than those allowed by the
array declaration, the index is said to be out of bounds
 An out of bounds index will cause a program to terminate with a run-time error
message
 Array indices get out of bounds most commonly at the first or last iteration of a loop
that processes the array: Be sure to test for this! 10
Loops to navigate and manipulate Arrays
 Arrays navigation and manipulation is mostly a repeatition of tasks:Hence
the need for loops
 Example creating and assigning an array of 100 scores to zero(0):
int scores[] = new scores[100];
for(int i=0;i<100;i++){
scores[i] = 0;
}

 Loops can the be used as follows :


• Reading values of an array from user input
• Displaying all values in a array
• Manipulation of values in array such as summing up all the values
11
Loops and Arrays:Examples
 Create and prompt for 10 student names into an array:
String studentNames[] = new String[10];
for(int i=0;i<10;i++){
System.out.println("Enter a name: ");
studentNames[i] = kbd.next();
}
 Print out all the names in the array:
for(int i=0;i<10;i++){
System.out.println( studentNames[i] );
}
12
Loops and Arrays: Exercises
 Create and prompt for 400 student marks into an array, then get
the sum and average.

 Print out all the marks in the array using another loop and later
print the sum and average.

13
Enhanced loop
 AKA the for-each is mainly used to cycle or navigate through any data
structures.
 This kind of loop can cycle through each element in a collection even
though the elements are not indexed.
 Syntax for a for-each loop statement :
for (ArrayDataType VariableName : ArrayName)
Statement
 Note that VariableName must be declared within the for-each loop, not
before
 Note also that a full colon (not a semicolon) is used after VariableName
14
Enhanced loop usage
 When the for-each is used for printing the following will become:
for(int i=0;i<10;i++){
System.out.println( studentNames[i] );
}//using normal for loop
for(String name:studentNames){
System.out.println( name);
}
 Read as "for each name in studentNames, do a system println of the
name”
 The for-each loop can make code cleaner and less error prone
 Note that the for-each syntax is simpler and quite easy to understand
15
Paired Arrays
 Refers to two or more arrays with the same sizes and mostly with
different data types, but related corresponding information,
 Example: Array for student names and student marks
 Mostly of the same size:
• String [] stundentNames = new String[10]
• int[] stundenAges= new int[10]
 Corresponding means:
• stundentNames[0] relates to studentAges[0] ….
 Paired arrays help us relate different information to one another
• Think about your individual assignment
16
Further Reading
 https://www.tutorialspoint.com/java/
• Mobile app available : Java Offline Tutorial
 https://www.tutorialspoint.com/java/java_arrays.htm
 https://www.javatpoint.com/array-in-java
 https://introcs.cs.princeton.edu/java/14array/
 http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/09/parallel-arrays.html
 https://www.youtube.com/watch?v=2n00B3pH6jM
 https://www.youtube.com/watch?v=5HDsOiyeSn0
 https://mathbits.com/MathBits/Java/arrays/ParallelArrays.htm
 Many many……many more out there !!!!
17
UPCOMING EVENTS
April

- EXTENDED (2 WEEKS WORK)


19
- Lab 06 – DUE DATE
- Before 23h59

April

18
- Test 02
- Time slots : TBA
- Venue: TBA

Вам также может понравиться