Lecture 7:
Arrays
CS110: Programming Language I
Table of contents
01 02
Array Basics Arrays and Methods
03 04
Two – Dimensional Array Two – Dimensional Array
Basics and methods
01
Array Basics
Can a Variable Hold More Than One Value?
❖ So far we have used many types of variables, but each
variable stores one value at a time: one int or one String or one
double.
❖ But there are times when you’ll need to hold more than one
value in a variable.
Example:
Read one hundred numbers, compute their average, and find out
how many numbers are above the average.
So, how do you solve this problem?
Arrays Can Provide a Solution
In Java, an array is an indexed container that holds a set of
values of a single type.
Arrays allow you to create a single identifier to organize many
items of the same date type
Each item in an array is called an element.
Elements can be either primitive types or reference types
(Strings).
Array Data Types
Arrays can be of any data type, but all elements have to share
the same type, such as:
I. Primitive
II. Reference
Arrays Are Accessed by Their Index
➢ You can access each element in an array by its numerical index or subscript.
➢ The index of the first element is 0.
➢ A 10-element array has 0 to 9 indices.
➢ An index must be a nonnegative integer.
➢ Can use an expression as an index
What is an array?
data structures
fixed length once created.
In java, Arrays are objects, so they’re considered reference
types.
Every array object knows its own length and stores it in a length
instance variable.
Declaring Array Variables
▪ To use an array in a program, you must
I. declare a variable to reference the array and
II. specify the arrays element type.
▪ The element Type can be any data type, and all elements in the
array will have the same data type.
Declaring an Array: Two Methods
▪ You can declare an array in two ways:
▪ Both syntaxes are equivalent.
Is Declaring an Array Sufficient?
▪ Declaring an array isn’t enough to begin using it in your program.
▪ Unlike declarations for primitive data type variables, the declaration
of an array variable does not allocate any space in memory for the
array. It creates only a storage location for the reference to an array.
▪ Before you use an array, you need to tell Java to create space in
memory for the elements that it will hold.
▪ If a variable does not contain a reference to an array, the value of
the variable is null. You cannot assign elements to an array unless it
has already been created.
Creating Arrays
▪ After an array variable is declared, you can create an array by using
the new operator and assign its reference to the variable
▪ For example, if you want to create an array to hold 100 integers,
you could do the following:
▪ Alternatively, you could perform these two lines in one step:
What Do the Code Snippets Do?
Array Initializers
▪ You can also declare and initialize the array in a single step with known
values:
▪ For example, declare arrays of types String and int:
▪ Notice that this method doesn’t specify size
▪ It’s assigned a size based on the number of elements between the braces {}.
Accessing Array Elements
➢ Arrays are sequential structures, meaning that items are stored one after
another in an array.
➢ You can access an individual element of an array by using a bracket
notation.
➢ For example, here’s how you get values from the ages array:
How Do You Set the Value of an Array Element?
➢ You can set values to the array’s elements like this:
➢ After you set the values to the elements at indices 0 and 1, the names array
looks like this:
Default Initialization of Arrays
When an array is created, its elements are assigned the default value of
➢ 0 for the numeric primitive data types,
➢ '\u0000' for char types
➢ false for boolean types.
How Do You Access the Length of an Array?
➢ So far, you created an array with a certain number of elements.
➢ After creation, you can’t change the length of an array.
➢ You can access the size of any array by using the array’s length
variable.
Exercise
➢ Declare a one-dimensional array named score of type int that can
hold 9 values.
➢ Declare and initialize a one-dimensional byte array named values of
size 10 so that all entries contain 1.
Homework!!!!
Using a for Loop to Traverse Arrays
➢ To iterate through, or traverse, an array means to process through each
element of the array by index number.
➢ You can use a for loop to traverse arrays.
➢ You can visit every array element by using the length variable of the array in
the iteration condition.
➢ Example: print the elements of the following array:
Exercise 2
What is the output of the following program?
Exercise 2 (cont.)
output:
Exercise 3 (self study)
Exercise 3 (self study)
Processing Arrays (Common Operations)
double [ ] myList = new double [ 10 ] ;
Initializing arrays with
input values
Initializing arrays with
random values between
0.0 and 100.0, but less
than 100.0
Printing arrays
Summing all elements
Processing Arrays (Common Operations)
double [ ] myList = new double [ 10 ] ;
Finding the largest
element
Copy to another array
Shifting Elements
Enhanced for Statement (for – each loop)
➢ You can use a enhanced for loop, an alternative to using the counter
controlled for loop, to iterate through an array.
➢ The enhanced for loop :
✓ Is also called as an enhanced for-each loop.
✓ Iterates through the elements of an array without using a counter, thus
avoiding the possibility of “stepping outside” the array.
✓ Can be used only to obtain array elements—it cannot be used to modify
elements.
Enhanced for Statement (for – each loop)
➢ Syntax:
➢ Example: print the elements of the following array by using enhanced for loop:
➢ For each iteration of the loop, the next element in the array is retrieved and
stored in an iteration-variable.
➢ The type must be the same as the elements stored in the array.
Enhanced for Loop vs. counter controlled for Loop
➢ Example:
Print the elements of the following array by using enhanced for loop and counter
controlled for loop:
Exercise 4
Exercise 5
➢ Enter the scores of 10 students by using a Scanner object.
➢ Display the scores that you entered.
➢ Calculate the average of the scores that you entered and print it
➢ Find the maximum and the minimum of the scores, and print
them.
Homework!!!!
02
Arrays and Methods
Passing Arrays to Methods
➢ To pass an array argument to a method, specify the name of the array without any
brackets.
➢ To receive an array, the method’s parameter list must specify an array parameter.
Pass-By-Value vs. Pass-By-Reference
Pass-by-value (call-by-value) Pass-by-reference (call-by-reference)
▪ For a parameter of an array type, the value of the parameter contains a
▪ For a parameter of a primitive type value, a copy of
reference to an array; this reference is passed to the method.
the argument’s value is passed to the called method.
▪ Any changes to the array that occur inside the method body will affect the
▪ The called method works exclusively with the copy.
original array that was passed as the argument. .
▪ Changes to the called method’s copy do not affect
▪ Improves performance by eliminating the need to copy possibly large
the original variable’s value in the caller.
amounts of data.
Pass-By-Value vs. Pass-By-Reference Example
Pass-By-Value vs. Pass-By-Reference Example
Pass-By-Value vs. Pass-By-Reference Example
Returning an Array from a Method
➢ A method may return an array.
➢ For example,
the following
method returns
an array that is
the reversal of
another array.
Case study: class average
➢ Write a java program that reads
10 student grades entered by the
user, computes their average, find
the maximum and minimum
grade. Use arrays to store the
grades and define three methods
03
Two – Dimensional Array Basics
Multidimensional Arrays
➢ Two-dimensional arrays are often used to represent tables of values consisting
of information arranged in rows and columns.
➢ Identify a particular table element with two indices.
➢ By convention, the first identifies
the element’s row and the second
its column.
➢ Multidimensional arrays can have
more than two dimensions.
Declare/Create Two-dimensional Arrays
➢ 1. Declare array ref var
syntax: datatype [ ][ ] refVar; example: int [ ][ ] matrix;
➢ 2. Create array and assign its reference to variable
syntax: refVar = new datatype [row][col];
example: matrix = new int [10][10];
➢ Or Combine declaration and creation in one statement
syntax: datatype [ ][ ] refVar= new datatype [10][10];
example: int [ ][ ] matrix = new int [10][10];
➢ Alternative syntax
int matrix [ ][ ] = new int [10][10];
Two-dimensional Array Illustration
➢ The index of each subscript of a two-dimensional array is an int value, starting from 0, to
rwos -1 and cols -1
Two-dimensional Array initializer
➢ You can also use an array initializer to declare, create and initialize a two-
dimensional array. For example,
int[ ][ ] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };
Same
as
int[ ][ ] array = new int[4][3];
array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
Lengths of Two-dimensional Arrays
int[ ][ ] x = new int [3][4];
➢ suppose x = new int[3][4], therefore, x[0], x[1], and x[2] are one-dimensional arrays and each
contains four elements, as shown.
➢ [Link] is 3 (number of rows), and
➢ x[0].length, x[1].length, and x[2].length are 4(number of elements in each row)
Lengths of Two-dimensional Arrays (cont.)
➢ The number of nested array initializers (represented by sets of braces within the
outer braces) determines the number of rows.
➢ The number of initializer values in the nested array initializer for a row determines
the number of columns in that row.
int[ ][ ] array = { [Link] is ?
{1, 2, 3}, array[0].length is ?
{4, 5, 6}, array[1].length is ?
{7, 8, 9}, array[2].length is ?
};
Ragged Arrays
➢ Each row in a two-dimensional array is itself an array. So, the rows can
have different lengths. Such an array is known as a ragged array.
➢ For example:
int[ ][ ] matrix = { [Link] is 5
{1, 2, 3, 4, 5},
matrix[0].length is 5
{2, 3, 4, 5},
{3, 4, 5},
matrix[1].length is 4
{4, 5}, matrix[2].length is 3
{5} matrix[3].length is 2
}; matrix[4].length is 1
Ragged Arrays
➢ If you don't know the values in a ragged array in advance, but do know the
sizes say, the same as before you can create a ragged array using the
following syntax:
Processing Two-Dimensional Arrays (Common Operations)
➢ Nested for loops are often used to process a two-dimensional array.
int [ ] [ ] matrix = new int [ 10 ] [ 10 ];
Initializing arrays with
input values
Initializing arrays with
random values between 0
and 99, but less than
100.0
Printing arrays
Processing Two-Dimensional Arrays (Common Operations)
➢ Nested for loops are often used to process a two-dimensional array.
int [ ] [ ] matrix = new int [ 10 ] [ 10 ];
Summing all elements
Summing elements by
column
Example
Example (cont.)
04
Two–Dimensional Array
and methods
Passing Two-Dimensional Arrays to Methods
➢ When passing a two-dimensional array to a method, the reference of the
array is passed to the method.
➢ You can pass a two-dimensional array to a method just as you pass a one-
dimensional array.
➢ You can also return an array from a method.
➢ Example
Passing Two-Dimensional Arrays to Methods Example
➢ Example
The following program gives an example with
two methods.
✓ The first method, getArray(), prompts the
user to enter values for the array (lines 11–24)
and returns a two-dimensional array, (line 23).
✓ The second method, sum(int[ ][ ] m), (lines
26–35) has a two-dimensional array
argument. You can obtain the number of rows
using [Link] (line 28) and the number of
columns in a specified row using
m[row].length (line 29)., returns the sum of all
the elements in a matrix.
That’s all for
this Lecture!!
Arrays
Array is a data structure that represents a collection of the same types of data.
Array’s length
➢ Once an array is
created, its size is
index
index
fixed. It cannot be
➢ An index must be
changed.
a nonnegative
integer. ➢ You can find its size
➢ Can use an using:
expression as an [Link]
index
In this example:
The value of
[Link] is 10
Case study
Write a java program that reads tree grades for
10 students, computes their average, find the
maximum and minimum grade. Use arrays to store
the grades and define three methods.
Code
Code
Code
Code
Code