[go: up one dir, main page]

0% found this document useful (0 votes)
7 views35 pages

17 Arrays

The document provides an overview of arrays in programming, explaining their structure, creation, and usage in languages like Java and C#. It outlines the steps to define, create, and initialize arrays, as well as methods for sorting and manipulating array data. Additionally, it discusses the concept of arrays as objects, their attributes, and common programming practices involving arrays.

Uploaded by

vembandasamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views35 pages

17 Arrays

The document provides an overview of arrays in programming, explaining their structure, creation, and usage in languages like Java and C#. It outlines the steps to define, create, and initialize arrays, as well as methods for sorting and manipulating array data. Additionally, it discusses the concept of arrays as objects, their attributes, and common programming practices involving arrays.

Uploaded by

vembandasamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Arrays

James
Click Brucker
to add Text
Arrays
An array is a series of elements of the same type, which
occupy consecutive memory locations.
float[] x = new float[10]; // array of 10 float vars
char[] c = new char[40]; // array of 40 char vars

Array x[] in memory:


x[0] x[1] x[2] . . . x[9]

4 Bytes = size of float


Array c[] = new char[40] in memory :
c[0] c[1] . . . c[39]

2 Bytes = size of char


Array is an Object
In C, C++, Fortran, etc., an array is just a collection of
sequential memory locations (as in previous slide).

x[0] x[1] x[2] . . . x[9]

In Java and C#, an array is an object.


This means an array can have methods and attributes,
such as the length of the array
Array x[] in Java is an object: it encapsulates data.
Array<float>
x is an array reference
length=10
x data is in an array object
float[0]=. . .
float[1]=. . .
Structure of an array
The first element has index 0.
An array has a fixed length (size cannot be changed).
float[] x = new float[10];
x[0] = 20;
x[1] = 0.5F;
x float[ ] (array)
length=10 array
[0]=20.0 object in
[1]= 0.5 memory
[2]= 0.0
...
[9]= 0.0
Array knows its own size!
Every array has an attribute named length
double[] x = new double[20];
x.length // returns 20
x.length is 20.
The first element is x[0],
the last element is x[x.length -1].

Don't forget -1 !

In Java, an array is an object.


length is a property (attribute) of the array object.
Why Use Arrays?

Make it easy to process lots of data using loops.

Perform operations on vectors and matrices.

Examples are given in later slides.


3 Steps to create an array
There are 3 steps to define & initialize an array.
Memorize them! A common programming error is to
omit one of these steps.
1. Define array String[ ] colors;
variable (reference) double[ ] x;

2. Create the array x=


& specify its size. new double[10]; colors =
new String[3];

3. Assign values to x[0] = 10.0; colors[0] = "red";


array elements. x[1] = 0.5; colors[1] = "blue";
... colors[2] = "green";
1. Define array reference
Declare p as type "array of int".
OK to omit space after "int" and between [ ].
<<memory>>
int [] p; p null

This creates an array reference p,


but does not create an array.

p does not refer to anything yet!


Just like:
String s;
defines a String reference but
does not create a string.
2. Create the Array object
Create the array using "new".
array = new DataType[ size ]
<<memory>>
p = new int[10]; p <object>

new object Array Storage in memory:

"new" creates a new object. int[]


01000 length=10
Here, it creates an array 01004
containing 10 "int" values. 01008
It sets p to refer to this object. 0100C 10 int's
01010
01014
....
3. Initialize elements of the array
When you create the array, Java does not initialize the
array elements. You must do this.
<<memory>>
for(int k=0; k < 10; k++) p <object>
p[k] = k;
Array storage in memory:

int[]
length=10
You can initialize array elements 0
any way you like. 1
2
Some examples in later slides. ...
Short-cut to create an Array
You can combine steps (1) and (2) into one statement:
<<memory>>
int[] p = new int[10]; p <object>

This statement does two things:


int[]
length=10
1) define p as an array reference 0
2) create an array with 10 0
0
elements and assign it to p ...
Another short-cut
If you have fixed values to put in the array, you can
combine steps 1 - 3 into one statement:
int[] p = { 2, 4, 6, 8, 10};
p <object>

This statement does 3 things:


int[]
length=5
1) define p as an array reference 2
2) create array with 5 int's 4
6
3) stores values 2, 4, ... 10 in the 8
array 10
Summary: steps to create array
1. Define an array reference:
double [] x;

2. Create the array (allocate storage for elements) :


x = new double[10];

3. Assign values to the array elements:


for(int k=0; k<x.length; k++) x[k] = 2*k;

Short-cut: define array reference and create object


double[] x = new double[10];
Meaning of [] in "String[] x"
The [ ] means "array of ..." or "... array".

int[] means "int array" or "array of int".

Foo[] means "Foo array" or "array of Foo".

int[ ] x; x is type "int array"


main(String[] args) args is type "String array"
char[] c = {'c','a','t'} c is type "char array"
double[] getScores() getScores returns
"array of double"
Read Data into an Array
Suppose we want to read some words from the input into an
array. Maybe we know that the input will never contain more
than 100 words. We could write...

// create Scanner to read input


Scanner input = new Scanner( System.in );
// create array of words (Strings)
String [ ] words = new String[100];
// read the data
int count = 0;
while(input.hasNext() && count < words.length)
{ words[count] = input.next( );
count++;
}
// now count = number of words actually read
Sort Data in an Array
java.util.Arrays - provides static methods for arrays.
One method is: Arrays.sort( array[] )

/** Sort the words[ ] array from last slide */


/** You must "import java.util.Arrays". */

Arrays.sort( words );

Input data Result:


dog words[0] = "ANT"
cat Arrays.sort( ) words[1] = "DOGS"
frog words[2] = "cat"
DOGS words[3] = "dog"
ANT words[4] = "frog"
Sort part of an Array
The previous slide is not quite correct.
Since we only have data for part of the array, we
should sort only that part. Use:
Arrays.sort(array[ ], start_index, end_index)

// sort elements 0 until count (exclusive)


Arrays.sort( words, 0, count );

This sorts only the elements


words[0] words[1] ... words[count-1]
Output the Elements of an Array
Now lets print the values of the array.
// write a loop to display each array element

for( int k=0; k < count ; k++ )


System.out.printf("%d: %s\n", k, words[k]);

Output:
0: ANT
1: DOGS
2: cat
3: dog
4: frog
An Array of Fibonacci Numbers
This example shows how to process all elements of an array.
The important point is that the "for" loop starts at k=0 and tests
k < fib.length (false when k=fib.length)

final int ARRAYSIZE = 20; // a constant value


long [ ] fib = new long[ ARRAYSIZE ];
fib[0] = fib[1] = 1;
for(int k = 2; k < fib.length; k++ )
fib[k] = fib[k-1] + fib[k-2];

// output the values


for(int k = 0; k < fib.length; k++ )
System.out.printf("f[%d] = %d\n",k, fib[k]);
Array as parameter
Use the same syntax as declaring an array variable.
/** Print the array elements. */
public void printArray( String[] array ) {
for(int k=0; k< array.length; k++)
System.out.printf("[%d] = %s\n",
k, array[k] );

/** Return maximum element in array. */


public double max( double[] array ) {
double max = array[0];
for(int k=1; k<array.length; k++) {
if (array[k] > max) max = array[k];
return max;
}
main has String array parameter
The main method accepts array of Strings.
/** args = command line arguments */
public static void main( String[] args ) {
for(int k=0; k < args.length; k++)
System.out.printf("args[%d] = %s\n",
k, args[k] );

The parameters to main are strings given on command line


when running the class in the JVM.
For example:
cmd> java MyClass hi there
args[0] = "hi"
args[1] = "there"
Method can return an array
A method can return an array:
/** Create an array and fill it with "1" */
static double[] makeOnes(int size) {
double x = new double[size];
// use Arrays.fill() is better
for(int k=0; k<size; k++) x[k] = 1.0;
return x;
}
Avoid this Common Mistake!
What does "b = a" do?
What will be printed?
int [] a = { 2, 4, 6, 8 };
int [] b = { 0, 0, 0 };
b = a; // What does this do?
b[2] = 999;
System.out.println( a[2] );
System.out.println("b.length=" + b.length );
An Array Variable is a Reference
<<memory>>
What does "b = a" do? a <object>
What will be printed?
int [] a = { 2, 4, 6, 8 }; b <object>

int [] b = { 0, 0, 0 }; int[]
length=4
b = a; // Does what? 2
b[2] = 999; 4
6
System.out.println(a[2]); 8
System.out.println(
int[]
"b.length=" + b.length ); length=3
0
0
0
"b = a" copies the reference, not the array
<<memory>>
b = a;
a <object>
makes b refer to same array as a.
b <object>
b = a; int[]
length=4
b[2] = 999;
2
System.out.println(a[2]); 4
999
System.out.println( 8
"b.length=" + b.length );
int[]
length=3
0
0
0
The result:
<<memory>>
b = a;
a <object>
b[2] = 999;
System.out.println(a[2]); b <object>
System.out.println( int[]
length=4
"b.length=" + b.length );
2
4
6
999 8
b.length = 4
int[]
length=3
0
0
0
How do you really copy an array?
Here is one solution:

int[] a = { 2, 4, 6, 8 };

// java.util.Arrays.copyOf( ... )
// creates a new array for copy.
int[] b = Arrays.copyOf( a, a.length );

See also: System.arraycopy( ... )


Really Copying An Array
<<reference>>
To copy the contents of an array,
a <object>
you must copy each element.
<<reference>>
// copy each element of array
b <object>
for(int k=0; k<a.length; k++)
Array<int>
b[k] = a[k];
length=4
2
This copies all elements of a. 4
6
8
There is an easier way:
System.arraycopy(a, 0, b, 0, 4); Array<int>
length=4
2
4
6
8
System.arraycopy
System.arraycopy( src, src_start, dest, dest_start, length)

copies elements from src array to dest array.


It copies length elements only.

// copy each element of array


System.arraycopy(a, 0, b, 0, a.length );
"foreach" version of "for" loop
To iterate over every element of an array you can use a
special "for" syntax.

int [] array = { 2, 4, 6, 8, 10 };

// Iterate over all elements in array.


// "for each x in array do ..."

for(int x: array) System.out.println( x );


Array
// array of coins
Coin[] coins;
coins = new Coin[10];
coins[0] = new Coin(5);
coins[1] = new Coin(20);
System.out.println( coins[4] ); // print null
Example: reverse a String
Write a method named reverse to reverse order of a String.
Example:
reverse("Hello there") returns "ereht olleH"
Algorithm:
H e l l o !
1. Convert the parameter (String)
to an array of characters. Use:
string.toCharArray( ) H e l l o !

2. Iterate over the 1st half of the char array. ! o l l e H


Swap characters with the 2nd half.

3. Convert char array into a String and return it. ! o l l e H


Creating an Array of Objects
// 1. define array reference
Date [ ] birthdays;
// 2. allocate storage
<<reference>>
birthdays = new Date[ 60 ];
// 3. create the objects birthdays <object>

// that go in the array!


for(int k=0; Object Storage Area:
k < birthdays.length; k++ )
Array<Date>
birthdays[k] = new Date( );
length=60
values= <Date>
Date ref
Date ref <Date>
birthdays[k] is an object reference.
Date ref
You must create the Date object that it ...
will refer to. Date ref <Date>
Example: Array of Objects (2)
Define a simple Student class with attributes for name and
Student ID.
public class Student {
String firstName; // attributes of student
String lastName;
String studentID;

/** constructor for new Student object */


public Student(String fn, String ln, String id)
{ studentID = id; // set the attributes
firstName = fs; // using parameters of
lastName = ls; // the constructor
}
... remainder of class definition omitted...
}
Example: Array of Objects (3)
We can create a new Student object like this:

Scanner input = new Scanner( System.in );

/* read data for a student */


String id = input.next( );
String first = input.next( );
String last = input.next( );

/* create a new student object */


Student s = new Student( first, last, id );

You might also like