[PDF] [PDF] Introduction to Arrays

int[] numbers = new int [3]; numbers[5] = 10; Answer: The index 5 is out of the bounds defined by the size declarator Java performs bounds checking 



Previous PDF Next PDF





[PDF] Arrays in Java

We assume you know about arrays in some language, like Python, Matlab, C, and so As in most programming languages, once created, the length of the array 



[PDF] What is an array?

Arrays are objects in Java ○ Even a public instance variable: length – Range of positions: 0 length-1 – Length is fixed after created (instantiated) ○ Declare 



[PDF] Introduction to Arrays

int[] numbers = new int [3]; numbers[5] = 10; Answer: The index 5 is out of the bounds defined by the size declarator Java performs bounds checking 



[PDF] Chapter 6 Arrays

When space for an array is allocated, the array size must be given, to specify the number of Java has a shorthand notation, known as the array initializer that combines declaring an array o (Finding the smallest index of the largest element)



[PDF] Single-Dimensional Arrays

When space for an array is allocated, the array size must be given, to specify the number of Java has a shorthand notation, known as the array initializer that combines declaring an array o (Finding the smallest index of the largest element)



[PDF] Arrays in Java – Using Arrays Recall – Length of an Array Once an

7 déc 2010 · length to determine the upper bound of the loop As we previously noted, the length field will return a value one greater than the maximum index 



[PDF] Arrays - Building Java Programs

to refer to your array, which means you can ask for temperature length to find out the length of the array By using temperature length in the for loop test instead 



[PDF] Arrays

Don't we know how big the array is from when we created it – length 100 or whatever? The answer is that length is useful, since it allows us to write a method that 



[PDF] Size of a Java int

int[] ages; Java Code What Happens? A new variable, ages, is created ages can ONLY hold an integer array (variable declaration) x = 5 Computer Memory

[PDF] how to learn formal languages and automata theory

[PDF] how to make 2 formalin

[PDF] how to make a map in google earth pro

[PDF] how to make a triangle symbol on mac

[PDF] how to make an element constructor in minecraft

[PDF] how to make angle symbol on mac

[PDF] how to make antidote in minecraft

[PDF] how to make chlorine in minecraft

[PDF] how to make foreign letters on keyboard mac

[PDF] how to make glow sticks glow brighter

[PDF] how to make phosphorus in minecraft

[PDF] how to make scientific figures for publication

[PDF] how to make scientific figures in powerpoint

[PDF] how to make symbols with keyboard

[PDF] how to master psychometric tests pdf

CS0007: Introduction to Computer Programming

Introduction to Arrays

Review

yA Conditionally-Controlled IRRS UHSHMPV" y as long as a particular condition exists. yA Count-FRQPUROOHG IRRS UHSHMPV" ya specific number of times. yA count-controlled loop has three elements yAn initialization expression yA test expression yAn update expression yThe difference between the prefix and postfix increment

RSHUMPRUV LV"

ypretest increments before the value of the operand is evaluated, posttest increments after the value of the operand is evaluated.

Review

y$Q MŃŃXPXOMPRU YMULMNOH LV" y a variable that keeps track of a running total. yA Sentinel Value LV" ya special value that cannot be mistaken for normal input that signals that a loop should terminate. ybreak LQ M ORRS" yPMNHV POH SURJUMP·V ŃRQPURO IORR JR PR POH VPMPHPHQP IROORRLQJ POH loop. ycontinue LQ M ORRS" yskips to the next iteration of the loop. yJava provides a class that generates pseudo-random numbers ŃMOOHG" yRandom

Arrays

ySo far we have worked primarily with primitive variables yOne characteristic of primitive variables is that they hold one value at a time. yint x = 100 ² can only hold one integer value at a time (100 at this time) yImagine that you want to hold the names of 100 people at a time. yWhat would you have to do? yDeclare 100 variables, one for each name. yBetter solution: Use Arrays. yArrays are complex variables that can hold multiple values of the same data type. yNow we can declare a single array that holds all the names.

yIn Java, Arrays are objects and behave very similarly (use new keyword to create the object, has methods, etc.)

Arrays

yTo declare an integer array: int[] numbers;

yIt is just like declaring any primitive variable, EXCEPT for the[] between the data type and the identifier.

yJust like any other object, this does not create the array, it creates a reference variable that can point to an array.

yTo create an array object for this reference variable: numbers = new int[6]; y7OH QXPNHU LQVLGH RI POH VTXMUH NUMŃNHPV LV ŃMOOHG POH MUUM\·V size declarator. y$Q MUUM\·V 6L]H GHŃOMUMPRU LQGLŃMPHV POH QXPNHU RI elements, or values the array can hold. yIndividual values inside of an array are called elements. ySo the numbers array can hold 6 integers. yYou can declare and create on the same line like any other object: int[] numbers = new int [6];

Arrays

yThe elements in an array are numbered starting from 0. ySo the first element has index 0. yThe size declarator must be a non-negative integer expression. yOften cases we know the size of the array when writing the code and can just use a literal. yHowever, it is common practice to use a constant as the size declarator. final int NUM_ELEMENTS = 6; double[] numbers = new double [NUM_ELEMENTS]; yOnce an array is created the size cannot change! yArrays can be of any type we discussed up to this point.

Accessing Array Elements

yEven though, the array has one name, we can access the individual elements by their index (or subscript).

y$Q HOHPHQP·V Index (or Subscript) is a uniquely identifying number that is used to pinpoint its position in the array.

ySo, if I want a specific element, I use its index. yAgain, indices start at 0.

yWhen you access an element in the array, you can use it just like MQ\ VLPSOH YMULMNOH RI POH MUUM\·V GHŃOMUHG P\SHB

yThe following statement assigns 20 to the first element in the numbers array: numbers[0] = 20;

yTo access an element of an array, simply use the array name IROORRHG N\ POH HOHPHQP·V LQGH[ LQVLGH RI VTXMUH NUMŃNHPVB

Array Example 1

yNew Topics: yArrays

Array Example 2

y7OLV VHHPV UHSHPLPLYH" yI have to use a separate segment of code for taking in the employees hours and for printing the result out. yIs there a better way? yAnswer: Yes, using loops. yArrays work great with loops, because you can loop through the elements of the array and perform operations on them. yNew Topic: yLooping through arrays

Bounds Checking and Off-by-One

Errors

yWhat is the problem with this? int[] numbers = new int [3]; numbers[5] = 10; yAnswer: The index 5 is out of the bounds defined by the size declarator. yJava performs bounds checking at runtime.

yIn the case with Java that means that if you attempt to index an element outside RI POH MUUM\·V NRXQGV LP RLOO POURR MQ H[ŃHSPLRQ ŃMXVH MQ HUURU MQG PHUPLQMPH your program).

yWe will not discuss exceptions in this course. yWhat is the problem with this? int[] numbers = new int [3]; numbers[3] = 10; yAnswer: 7OH LQGH[ 3 LV VPLOO RXP RI POH MUUM\·V NRXQGVB yBecause indexing starts at 0, the last element of the array is the size of the array minus 1. yThis is called an Off-by-One error.

Array Declaration Notes

yYou can initialize Arrays just like any other variables. int[] numbers = {1, 2, 3, 4, 5};

yThis array has an implicit size of 5 and the values in the initialization are indexed from left to right.

yExample: ArrayInitialization.java yJava also allows for two different syntactical forms for declaring an array: int[] numbers; int numbers[]; yThe difference is when you declare multiple arrays on the same line: int[] numbers1, numbers2, numbers3; yThis declares three reference variables to integer arrays int numbers1[], numbers2, numbers3; yThis declares one reference variable to an integer array and two primitive integer variables int numbers1[], numbers2[], numbers3[]; yThis, again, declares three reference variables to integer arrays

Array Elements

yIndividual array elements can be treated like any simple variable of that type. int[] numbers = new int[5]; int x = 5; numbers[1] = x + 5; x = numbers[1] + 20; numbers[2] = numbers[1] / 5; numbers[2]++; yAlso, since arrays are objects in Java, they have methods and data members. yFor instance the length data member holds the number of elements in the array. yint size = numbers.length; yThis is helpful for looping through an array.

Enhanced for Loop

yThe last kind of loop we will be discussing in this course is called the enhanced for loop.

yThe Enhanced for Loop is a special loop that iterates through the elements in a collection (in this case array) and allows access to each element.

yEach iteration of the loop corresponds to an element in the array. yGeneral Form: for(dataType elementVariable : array) block or statement ydataType ² The type of the array yelementVariable ² A variable that holds the value of the ŃXUUHQP LPHUMPLRQ·V HOHPHQPB yarray ² The array in which we are iterating through.

Enhanced for Loop Example

yNew Topics: yEnhanced for Loop

When NOT To Use the Enhanced for

Loop yThe enhanced for loop is useful for when you need only all the values of the array, but there are many situations when you should NOT use it:

1.If you need to change the contents of an array element

2.If you need to work through the array elements in reverse

order

3.If you need to access some of the array elements, but not all

of them

4.If you need to simultaneously work with two or more arrays

within the loop

5.If you need to refer to the index of a particular element

yIf any of these cases apply, use a regular for loop. $OORRLQJ POH 8VHU PR 6SHŃLI\ MQ $UUM\·V Size ySince the size declarator is an integer, you can let the user enter an integer, and then create an array of that size. yExample: UserSizeArray.java

Reassigning Reference Variables and

Array Copying

yAs stated before, you cannot change the size of an array once it has been set. yYou can, however, make the reference variable point to a new array. int[] numbers = {1, 2, 3, 4, 5}; numbers = new int [10]; yWhat is the problem with this? yNow numbers has no values in it!

yWhat you need to do is copy the elements of the old array to the new one, and make the original reference variable point to the new array:

1.Create a new reference variable

2.Make the new reference variable point to an array of the newly specified size

3.Use a loop to assign the elements from the old array to the new one.

4.Assign the new reference variable to the old one.

Array Copying Example

yNew Topics: yArray Copyingquotesdbs_dbs4.pdfusesText_8