11-05-2013

posted Nov 6, 2013, 8:42 AM by Samuel Konstantinovich   [ updated Nov 6, 2013, 12:08 PM ]
Goal: Arrays in java [like lists in python but not as cool]


Today you should work on arrays and if/when you finish you can work on your princess/pony addon to your assignment. 

In other languages you may have seen some kind of list. 
In scheme '(1 2 3) is a list. 
In python (1, 2, 3) is a list.

The lowest level list we have in java are not called lists, we call them arrays.

Array:
A continuous block of memory used to store multiple values of the same type
Individual values in an array can be referenced by their index (position in the array)
Arrays use 0 based indexing (max index is always 1 less than length of array)

Pun of the day: 
Arrays in in the sun. -Z

Array Declaration:

//type[] variable_name;
int[] intlist;


to set size of array: 
//variable_name
 = new int [size of array];
intlist = new int[10];

The size of array can be any positive integer.
array size cannot be changed

int[] a;
a = new int [5];

Lets say we initialized a as follows:
a:
 5  
(index: 0)
 12
(1)
 -8
(2)
 0
(3)
 17
(4)
(Note: the number below in parenthesis is the index)

We use the [ ]'s to get to any specific value in an array
a[index] (read as "a sub 'index')
a[2] evaluates to
 -8 

a[2] + 3  is an expression (not a statement) that evaluates to - 5 but doesn't change the array:
a:
 5  
(index: 0)
 12
(1)
 -8
(2)
 0
(3)
 17
(4)

a[3] = 12; this is a statement that modifies a[3] so that we have: 
a:
 5  
(index: 0)
 12
(1)
 -8
(2)
 12
(3)
 17
(4)

By default, the values in an array for any numeric primitive are all 0
By default, the values in an array of objects are null

a.length returns number of allocated spaces of the array. This is the number you used to declare it.

To print the contents of arrays, or find the sum, or any other operation that works on all elements, we need to write code that loops through all the values. 

Easy Array Problems:
http://codingbat.com/java/Array-1

Normal Array Problems:
http://codingbat.com/java/Array-2

Complete these normal problems as a warm up: (if they are hard, go do some easy ones as practice)
sum 13 http://codingbat.com/prob/p127384
Centered Average  http://codingbat.com/prob/p136585
FizzBuzz: http://codingbat.com/prob/p153059

Harder Array Problems:
http://codingbat.com/java/Array-3

You should Complete at least 2 of the harder problems: 
Count clumps: http://codingbat.com/prob/p193817
Can Balance: http://codingbat.com/prob/p158767
Max Mirror: http://codingbat.com/prob/p196409
Max Span: http://codingbat.com/prob/p189576



Comments