Lecture 4

Fall 2018
Narges Norouzi
Recap
-
User Input
-
Conditionals
-
if-statement
-
Nested if-statements
-
switch-case statements
-
-
Loops
-
while loop
-
do-while loop
-
for loop
-
Break & Continue
-
Break:
- Jumps out of a block
-
Continue:
- Jumps to the beginning of the block


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

Break
Multi-dimensional Arrays
Two-dimensional array
-
Examples:
-
Table of grades for each student and assignment
-
Table of data for each experiment and outcome
-
-
Mathematical abstraction: Matrix
-
Java abstraction: 2D array
Two-dimensional arrays in java
-
Array Access: use a[i][j] to access element in row i and column j.
-
Zero-based indexing: Row and column indices start at 0.
2D array or Array of Arrays

Example



Demo
Matrix Addition
Zybooks chapters we covered
- Chapter 4 part 4.9
- Chapter 5 up to and including 5.9
Copy of CMPS12A - Lecture 4
By Narges Norouzi
Copy of CMPS12A - Lecture 4
- 389