posted Sep 25, 2018, 5:58 AM by Konstantinovich Samuel   [ updated Sep 25, 2018, 8:28 AM ]

Homework! (more coding bat)

Exam friday: All of java up to arrays. We will go over various problems tomorrow in class.
You are free to discuss algorithms for the coding bat on the google group.


Java's way of storing a group of the same type of values is called an Array

class ArrayDemo { public static void main(String[] args) { // declares an array of integers int[] anArray; // allocates memory for 10 integers anArray = new int[10]; // initialize first element anArray[0] = 100; // initialize second element anArray[1] = 200; // and so forth
        anArray[2] = 300;
        System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]);

The output from this program is:

Element at index 0: 100
Element at index 1: 200
Element at index 2: 300

Let us look at the various parts

Declaring a Variable to Refer to an Array

The preceding program declares an array (named anArray) with the following line of code:

// declares an array of integers int[] anArray;
An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty).

Alternatively, you can use the shortcut syntax to create and initialize an array but only at the same time as the declaration:

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000

Here the length of the array is determined by the number of values provided between braces and separated by commas.

You can look at the length using variablename.length   which is NOT a method, there are no parenthesis


Array.length is often used in other constructs like if statements or loops:


if( anArray.length > 10) {



You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets, such as String[][] names. We will deal with this later.

This is NOT how you should do things:
        anArray[0] = 100;
        anArray[1] = 200; anArray[2] = 300; anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000;

Replace with:
loop that uses i{
        anArray[i] = ????;

Everyone Right now:
Initialize an array of 11 elements.
Create a for loop that will initialize this array with 100 through 200 (increments of 10.

public class ArrayTest{
   public static void main(String[]args){
        //int[] anArray = ???
        //Write the loop to initialize it
        //Write a loop to print it out (on one line)


[ 100, 110, 120, ... 200]

HW: Do as many as you can, but we will have some time in class to work on it tomorrow

Arrays-1 (no loops, very silly warmup... )