1D Arrays

Recap
-
User Input
-
Conditionals
-
if-statement
-
Nested if-statements
-
switch-case statements
-
-
Loops
-
while loop
-
do-while loop
-
for loop
-
Arrays

Array
-
Indexed sequence of values of the same type
-
Example:
-
52 playing cards in a deck
-
1 million characters in a book
-
130 students in this course sorted by their ID
-

Many Variables of Same Type
Goal: 10 variables of type int

Many Variables of Same Type
Goal: 10 variables of type int

Declares, creates, and initializes values
Arrays in java
-
To make an array, declare, create and initialize it.
-
To access element 'i' of an array named ‘a’, use a[i].
-
Array indices start at 0.

Example

compact alternative
-
Declare, create, and initialize in one statement.
-
Default initialization: all numbers automatically set to 0.


Explicit Initialization
- Example
- Equivalent to



Demo
Dot product of two vectors
Length of the array
- We can get the length of the array using the length field:
- Can be used for iteration over array elements


Consider
- Defined an array to reference a list of 100 integers
- Each element is initialized by default to 0
-
Two exceptions will be thrown here:
- -1 is not a valid index – too small
-
100 is not a valid index – too large
- IndexOutOfBoundsException

Due soon
- program 1 tonight
- no class Monday
- 5.9, 5.10 Wednesday
- 2.14,3.12-3.15,4.6 Friday
Copy of 1D Arrays
By Narges Norouzi
Copy of 1D Arrays
- 261