CS1001

29
1 CS1001 CS1001 Lecture 14 Lecture 14

description

CS1001. Lecture 14. Overview. Java Programming Arrays. Goals. Understand the basics of Java programming Control Statements and Arrays. Assignments. Brookshear: Ch 4, Ch 5 (Read) Read linked documents on these slides (slides will be posted in courseworks). Arithmetic. - PowerPoint PPT Presentation

Transcript of CS1001

Page 1: CS1001

11

CS1001CS1001

Lecture 14Lecture 14

Page 2: CS1001

22

OverviewOverview

Java ProgrammingJava Programming ArraysArrays

Page 3: CS1001

33

GoalsGoals

Understand the basics of Java Understand the basics of Java programmingprogramming

Control Statements and ArraysControl Statements and Arrays

Page 4: CS1001

44

AssignmentsAssignments

Brookshear: Ch 4, Ch 5 (Read)Brookshear: Ch 4, Ch 5 (Read) Read linked documents on these Read linked documents on these

slides (slides will be posted in slides (slides will be posted in courseworks)courseworks)

Page 5: CS1001

55

ArithmeticArithmetic Operators: Operators: ++, , --, , //, , ** , , %%

The precedence of operators and The precedence of operators and parentheses work the same way as in parentheses work the same way as in algebra.algebra.

m % nm % n means the remainder when means the remainder when mm is divided by is divided by nn (e.g. 17 % 5 is 2). (e.g. 17 % 5 is 2).

%% has the same rank as has the same rank as // and and **

Same-rank binary operators are Same-rank binary operators are performed in order from left to right.performed in order from left to right.

Page 6: CS1001

66

Arithmetic (cont’d)Arithmetic (cont’d)

The type of the result is determined by The type of the result is determined by the the typestypes of the operands, not their of the operands, not their values; this rule applies to values; this rule applies to all all intermediate resultsintermediate results in expressions. in expressions.

If one operand is an If one operand is an intint and another is a and another is a doubledouble, the result is a , the result is a doubledouble; if both ; if both operands are operands are intints, the result is an s, the result is an intint..

Page 7: CS1001

77

Arithmetic (cont’d)Arithmetic (cont’d)

Caution:Caution: if if aa and and bb are are intints, then s, then a a // b b is is truncatedtruncated to an to an intint……

1717 // 5 gives 5 gives 33 33 // 4 gives 4 gives 00

……even if you assign the result to a even if you assign the result to a doubledouble::

double ratio = 2double ratio = 2 // 3; 3;The double type of the result doesn’t help: ratio still gets the value 0.0.

Page 8: CS1001

88

Arithmetic (cont’d)Arithmetic (cont’d) To get the correct To get the correct doubledouble result, use result, use doubledouble

constants or the constants or the castcast operator: operator:

double ratio = double ratio = 2.02.0 // 3; 3;

double ratio = 2double ratio = 2 // 3.03.0;;

double factor = double factor = (double)(double) m m // (double)(double) n; n;

double factor = mdouble factor = m // (double)(double) n; n;

double r2 = kdouble r2 = k // 2.02.0;;

double r2 = double r2 = (double)(double) k / 2; k / 2;Casts

Page 9: CS1001

99

Arithmetic (cont’d)Arithmetic (cont’d) Caution: Caution: the range for the range for intints is from s is from

--223131 to 2 to 23131--1 (about 1 (about --2·102·1099 to to 2·102·1099))

Overflow is Overflow is notnot detected by the Java detected by the Java compiler or interpretercompiler or interpretern = 8 10^n = 100000000 n! = 40320n = 9 10^n = 1000000000 n! = 362880n = 10 10^n = 1410065408 n! = 3628800n = 11 10^n = 1215752192 n! = 39916800n = 12 10^n = -727379968 n! = 479001600n = 13 10^n = 1316134912 n! = 1932053504n = 14 10^n = 276447232 n! = 1278945280

Page 10: CS1001

1010

Arithmetic (cont’d)Arithmetic (cont’d)

Use compound Use compound assignment assignment operators:operators:

a a == a a ++ b; b; a a +=+= b; b;

a a == a a -- b; b; a a -=-= b; b;

a a == a a ** b; b; a a *=*= b; b;

a a == a a // b; b; a a /=/= b; b;

a a == a a %% b; b; a a %%== b; b;

Use increment Use increment and decrement and decrement operators:operators:

a a == a a ++ 1; 1; a a++++;;

a a == a a -- 1; 1; a a----;;

Do not use these in larger expressions

Page 11: CS1001

1111

Review:Review: What is a variable? What is a variable? What is the type of variable that holds What is the type of variable that holds

an object?an object?

Page 12: CS1001

1212

Review (cont’d):Review (cont’d): What is the range for What is the range for intints?s? When is a cast to When is a cast to doubledouble used? used? GivenGiven

double dF = 68.0;double dF = 68.0;double dC = 5 double dC = 5 / / 9 9 ** (dF (dF -- 32); 32);

what is the value of what is the value of dCdC?? When is a cast to When is a cast to intint used? used? Should compound assignment Should compound assignment

operators be avoided?operators be avoided?

Page 13: CS1001

1313

Objectives:Objectives:

Learn about arrays and when to use Learn about arrays and when to use themthem

Learn the syntax for declaring and Learn the syntax for declaring and initializing arraysinitializing arrays

Learn how to access array’s size Learn how to access array’s size and elementsand elements

Page 14: CS1001

1414

What is an ArrayWhat is an Array

An array is a block of consecutive memory An array is a block of consecutive memory locations of the same data type.locations of the same data type.

Individual locations are called array’s Individual locations are called array’s elementselements..

Sometimes when we say “array’s element” we Sometimes when we say “array’s element” we mean the mean the valuevalue stored in that element. stored in that element.

1.39

1.69

1.74

0.0

An array of doubles

Page 15: CS1001

1515

What is an Array What is an Array (cont’d)(cont’d)

Rather than treating each element as Rather than treating each element as a separate named variable, the whole a separate named variable, the whole array gets array gets oneone name. name.

Specific array elements are referred to Specific array elements are referred to by using array’s name and the by using array’s name and the element’s number, called element’s number, called indexindex or or subscriptsubscript..

c[0] c[1] c[2] c[3]

1.39

1.69

1.74

0.0 o is array’s

name

Page 16: CS1001

1616

Indices Indices (Subscripts)(Subscripts)

In Java, an index is written within square In Java, an index is written within square brackets following array’s name (e.g., brackets following array’s name (e.g., a[k]a[k]).).

Indices start from 0; the first element of Indices start from 0; the first element of an array an array aa is referred to as is referred to as a[0]a[0] and the and the nn--th element as th element as a[n-1]a[n-1]..

An index can have any An index can have any intint value from 0 to value from 0 to array’s length array’s length -- 1. 1.

Page 17: CS1001

1717

Indices Indices (cont’d)(cont’d)

We can use an We can use an intint variable or any variable or any expression that evaluates to an expression that evaluates to an intint value as an index:value as an index:

a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ]

Page 18: CS1001

1818

Indices Indices (cont’d)(cont’d)

In Java, an array is declared with In Java, an array is declared with fixed length that cannot be changed.fixed length that cannot be changed.

Java interpreter checks the values of Java interpreter checks the values of indices at run time and throws indices at run time and throws IndexOutOfBoundsExceptionIndexOutOfBoundsException if an if an index is negative or if it is greater index is negative or if it is greater than the length of the array than the length of the array -- 1. 1.

Page 19: CS1001

1919

Why Do We Need Why Do We Need Arrays?Arrays? The power of arrays comes from the fact The power of arrays comes from the fact

that the value of a subscript can be that the value of a subscript can be computed and updated at run time.computed and updated at run time.

int sum = 0;sum += score0;sum += score1;…sum += score999;

Before (no arrays):

int n = 1000;int sum = 0, k;

for (k = 0; k < n; k++) sum += scores[k];

After (with arrays):

1000times!

Page 20: CS1001

2020

Why Arrays? (cont’d)Why Arrays? (cont’d) Arrays give Arrays give direct accessdirect access to any to any

element — no need to scan the array.element — no need to scan the array.

if (k == 0) display (score0);else if (k == 1) display (score1);else … // etc.

Before (no arrays):

display (scores[k]);

After (with arrays):

Page 21: CS1001

2121

Arrays as ObjectsArrays as Objects In Java, an array is an object. If the In Java, an array is an object. If the

type of its elements is type of its elements is anyTypeanyType, the , the type of the array object is type of the array object is anyType[ ]anyType[ ]..

There are two ways to declare an array:There are two ways to declare an array:

anyType [ ] arrName; The difference becomes significant only when several variables are declared in one statement:

int [ ] a, b; // both a, b are arrays

int a [ ], b; // a is an array, b is notanyType arrName [ ];

or

Page 22: CS1001

2222

Arrays as Objects Arrays as Objects (cont’d)(cont’d) As with other objects, the declaration As with other objects, the declaration

creates only a reference, initially set to creates only a reference, initially set to nullnull. . An array must be created before it can be An array must be created before it can be used.used.

There are two ways to create an array:There are two ways to create an array:

arrName = new anyType [ length] ; Brackets, not parens!

or

arrName = new anyType [ ] { val1, val2, …, valN };

Page 23: CS1001

2323

Declaration and Declaration and InitializationInitialization When an array is created, space is When an array is created, space is

allocated to hold its elements. If a list allocated to hold its elements. If a list of values is not given, the elements get of values is not given, the elements get the default values.the default values.

scores = new int [10] ; // length 10, all values set to 0

words = new String [10000]; // length 10000, all values set to null

Page 24: CS1001

2424

Initialization (cont’d)Initialization (cont’d) An array can be declared an initialized in An array can be declared an initialized in

one statement:one statement:

int scores [ ] = new int [10] ; // length 10

private double gasPrices [ ] = { 1.49, 1.69, 1.74 };

String words [ ] = new String [10000];

String cities [ ] = {"Atlanta", "Boston", "Cincinnati" };

Page 25: CS1001

2525

Initialization (cont’d)Initialization (cont’d) Otherwise, initialization can be postponed Otherwise, initialization can be postponed

until later:until later:

String words [ ]; // not yet initialized ... words = new String [ console.readInt() ];

private double gasPrices [ ]; // not yet initialized … gasPrices = new double [ ] { 1.52, 1.69, 1.75 };

Page 26: CS1001

2626

Array’s LengthArray’s Length The length of an array is determined when The length of an array is determined when

that array is created.that array is created.

The length is either given explicitly or The length is either given explicitly or comes from the length of the comes from the length of the {…}{…} initialization list.initialization list.

The length of an array The length of an array arrNamearrName is referred is referred to in the code as to in the code as arrName.lengtharrName.length..

lengthlength appears like a public appears like a public fieldfield (not a (not a method) in an array object.method) in an array object.

Page 27: CS1001

2727

Review:Review: Why are arrays useful?Why are arrays useful? What types of elements can an array What types of elements can an array

have?have? How do we refer to an array’s How do we refer to an array’s

element in Java?element in Java? What happens if an index has an What happens if an index has an

invalid value?invalid value? How do we refer to the length of an How do we refer to the length of an

array?array?

Page 28: CS1001

2828

SortingSorting

Page 29: CS1001

2929

Alternate Sorting Alternate Sorting AlgorithmAlgorithm(Selection Sort)(Selection Sort)main(String[] args) {main(String[] args) {

int inputSize = args.length;int inputSize = args.length;int[] sortedArray = new int[inputSize];int[] sortedArray = new int[inputSize];for (i=0; i < inputSize; i++) {for (i=0; i < inputSize; i++) {

(1) Loop through args, find largest element (1) Loop through args, find largest element and and remember its index (ie for (int j = 0; …))remember its index (ie for (int j = 0; …))(2) Put the largest element into the ith location (2) Put the largest element into the ith location of sortedArray;of sortedArray;(3) Delete (set to -1) the ith element of args(3) Delete (set to -1) the ith element of args

}}

http://http://www.ee.unb.ca/brp/lib/java/selectionsortwww.ee.unb.ca/brp/lib/java/selectionsort//