+ All Categories
Home > Documents > COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

Date post: 26-Mar-2015
Category:
Upload: sara-mcmillan
View: 220 times
Download: 1 times
Share this document with a friend
Popular Tags:
38
COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014
Transcript
Page 1: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110:Introduction to Programming

Tyler JohnsonMar 25, 2009

MWF 11:00AM-12:15PMSitterson 014

Page 2: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20092

Announcements

Lab 6 due tomorrow by midnight

Page 3: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20093

Questions?

Page 4: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20094

Today in COMP 110

Array Basics

Programming Demo

Page 5: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20095

Array Basics

Section 7.1 in text

Page 6: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20096

Recall from Lab 4

A program to read in a list of basketball scores from the user and output statistics

System.out.println("Enter the list of basketball scores " + "(enter a negative number to end your list): ");

while(score >= 0) { score = keyboard.nextInt()); totalGames++; scoreSum += score; //for computing the average}

if (totalGames > 0) { double average = (double) scoreSum / (double) totalGames; System.out.println("Average score: " + average);}

Page 7: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20097

What if…

…we wanted to know which of the scores entered were

Above average?Below average?

How would we do it?Can only compute average after we have all scoresWe need to look at previous scores

Let’s simplify this first

Page 8: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20098

One Possibility…

Assume exactly 5 scoresSystem.out.println("Enter 5 basketball scores:");

int score1 = keyboard.nextInt();int score2 = keyboard.nextInt();int score3 = keyboard.nextInt();int score4 = keyboard.nextInt();int score5 = keyboard.nextInt();

double average = (double) (score1 + score2 + score3 + score4 + score5) / 5.0;

System.out.println("Average score: " + average);

//repeat this for each of the 5 scoresif(score1 > average) System.out.println(score1 + ": above average");else if(score1 < average) System.out.println(score1 + ": below average");else System.out.println(score1 + ": equal to the average");

Page 9: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20099

What If We Had 80 Scores?

System.out.println("Enter 80 basketball scores:");

int score1 = keyboard.nextInt();int score2 = keyboard.nextInt();int score3 = keyboard.nextInt();// ...are we done yet?int score23 = keyboard.nextInt();int score24 = keyboard.nextInt();int score25 = keyboard.nextInt();// ...how about now?int score67 = keyboard.nextInt();int score68 = keyboard.nextInt();// ...still going…int score80 = keyboard.nextInt();// ...whew!

double average = (double) (score1 + score2 + score3 + score4 + ... score23 + score24 + score25 + ...) / 80.0;System.out.println("Average score: " + average);// now do below/above average check for all 80 scores

Page 10: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200910

Arrays

There’s a much easier way

Use an array!

Like a list of variables, but with a convenient, compact way to name them

A special kind of object in Java used to store a collection of data

Page 11: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200911

Creating an Array

int[] scores = new int[5]; //create 5 ints

This creates an array called “scores” that holds five integer values

scores[0] //a single integer, the 1st integer in the arrayscores[1] //a single integer, the 2nd integer in the arrayscores[2]scores[3]scores[4] //a single integer, the 5th and last integer in the array

Page 12: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200912

Indexing

Variables such as scores[0] and scores[1] that have an integer expression in square brackets are known as:

indexed variables, subscripted variables, array elements, or simply elements

An index or subscript is an integer expression inside the square brackets that indicates an array element

Page 13: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200913

Indexing

Where have we seen the word index before?

Strings are indexed

Index numbers start with 0. They do NOT start with 1 or any other number

U N C i s G r e a t

0 1 2 3 4 5 6 7 8 9 10

11

Page 14: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200914

Indexing

Array elements can be used just like any other variable of the same type

scores[3] = 68;scores[4] = scores[4] + 3; // just made a 3-pointer!System.out.println(scores[1]);

Page 15: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200915

Vector Example

double[] vector = new double[3]; //an array of 3 doubles (x, y, z)

vector[0] = 1.; //set the x valuevector[1] = 56.; //set the y valuevector[2] = 101.; //set the z value

//compute the length of the vectordouble length = Math.sqrt(vector[0]*vector [0] + vector [1]*vector

[1] + vector [2]*vector [2]);

//normalize the vectordouble[] vectorN = new double[3];vectorN[0] = vector[0]/length;vectorN[1] = vector[1]/length;vectorN[2] = vector[2]/length;

(x,y,z)

Page 16: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200916

Arrays

The array itself is referred to by a name “scores” or “vector” (in our examples)

0 1 2 3 4

68 73 57 102 94

Indices

the array scoresscores[3]

Page 17: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200917

Indexing

The index (value in square brackets) does not have to be a simple integer

It can be any expression that evaluates to an integer

int[] scores = new int[5];//initialize all scores to 0for(int index = 0; index < 5; index++) scores[index] = 0;

for(int index = 0; index < 5; index++) scores[index/2] = 0;

Page 18: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200918

Array Terminology

scores[index/2] = 0;

Array name

Index

Indexed Variable

Page 19: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200919

Reading in Scores

System.out.println("Enter 5 basketball scores:");

int[] scores = new int[5];int scoreSum = 0;

for(int i = 0; i < 5; i++) { scores[i] = keyboard.nextInt(); scoreSum += scores[i];}

double average = (double) scoreSum / 5;System.out.println("Average score: " + average);

for(int i = 0; i < 5; i++) { if(scores[i] > average) System.out.println(scores[i] + ": above average"); else if(scores[i] < average) System.out.println(scores[i] + ": below average"); else System.out.println(scores[i] + ": equal to the average");}

Page 20: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200920

Array Details

Syntax for creating an array:Base_Type[] Array_Name = new Base_Type[Length];

Example:int[] pressure = new int[100]; //create 100 variables of type int

that can //be referred to collectively

Alternatively:int[] pressure; //declare an integer array called pressurepressure = new int[100]; //allocate memory for the array to hold

100 ints

Page 21: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200921

Array Details

The base type can be any typedouble[] temperature = new double[7];Student[] students = new Student[35];Pet[] myPets = new Pet[3];

The number of elements in an array is its length, size, or capacity

temperature has 7 elements, temperature[0] through temperature[6]

students has 35 elements, students[0] through students[34]

myPets has 3 elements, myPets[0] through myPets[2]

Page 22: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200922

Use a Named Constant

Use a named constant instead of an int literal when creating an array

Poor programming practice

int[] pressure = new int[100];

Good programming practice

public static final int NUMBER_OF_READINGS = 100;int[] pressure = new int[NUMBER_OF_READINGS];

Page 23: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200923

Use a Named Constant

Why is it poor programming practice to use an int literal for the size?

It can be error proneYou may have to change multiple places in the code whenever you change the length of the array

int[] pressure = new int[100];

for(int index = 0; index < 100; index++) scores[index] = 0;

Page 24: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200924

Determining the Length

If you’re not sure what the length should be, consider reading it in from the keyboard

System.out.println("How many scores?");int numScores = keyboard.nextInt();int[] scores = new int[numScores];

Page 25: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200925

Array Length

An array is a special kind of object

It has one public instance variable: length

length is equal to the length of the arrayPet[] pets = new Pet[20];int sizeOfArray = pets.length; //sizeOfArray will have the value

20

You cannot change the value of length (it is final)

Page 26: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200926

Our Previous Example

System.out.println("Enter 5 basketball scores:");

int[] scores = new int[5];int scoreSum = 0;

for(int i = 0; i < scores.length; i++) { scores[i] = keyboard.nextInt(); scoreSum += scores[i];}

double average = (double) scoreSum / scores.length;System.out.println("Average score: " + average);

for(int i = 0; i < scores.length; i++) { if(scores[i] > average) System.out.println(scores[i] + ": above average"); else if(scores[i] < average) System.out.println(scores[i] + ": below average"); else System.out.println(scores[i] + ": equal to the average");}

Better than using the value 5 everywhere because it’s

not obvious where it comes from and its value may

change!

Page 27: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200927

For Loops and Arrays

For loops are often perfectly suited to processing arrays

Why?Because we know the number of iterations (array.length)

int[] pressure = new int[100];for(int index = 0; index < pressure.length; index++) scores[index] = 0;

Page 28: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200928

Be Careful with Indices

Indices MUST be in bounds

double[] entries = new double[5];entries[5] = 3.7;

Your code WILL compile with an out-of-bounds index

But it will result in a run-time error (crash)

//RUN-TIME ERROR! Index out of bounds

Page 29: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200929

Out of Bounds Example

System.out.println("Enter up to 10 scores");System.out.println("End your input with a negative number");

int scores = new int[10];

Scanner keyboard = new Scanner(System.in);int currScore = keyboard.nextInt();int i = 0;

while(currScore >= 0) {scores[i] = currScore ;i++;number = keyboard.nextInt();

}

Crash if more than 10 scores are

entered!

Page 30: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200930

Initializing Arrays

You can initialize arrays when you declare them

int[] scores = {68, 97, 102};

Equivalent to

int[] scores = new int[3];scores[0] = 68;scores[1] = 97;scores[2] = 102;

Page 31: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200931

Exercise

What is the output?

int[] anArray = new int[10];

for(int i = 0; i < anArray.length; i++)anArray[i] = 2*i;

for(int i = 0; i < anArray.length; i++)System.out.println(anArray[i] + " ");

0 2 4 6 8 10 12 14 16 18

Output

Page 32: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200932

Arrays & Methods

Arrays can be used with methods just like other objects can

Arrays can be passed as arguments to methodsArrays can be returned from methods

The main method takes in an array as an argument

public static void main(String[] args) { … }

An array of Strings

Page 33: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200933

Arrays as Arguments

Example

//init all array elements to 0public void initArray(int[] array) {

for(int i = 0; i < array.length; i++) array[i] = 0;

}

Page 34: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200934

Returning Arrays

Example

//create an array of the given size and return itpublic int[] createArray(int size) {

int[] array = new int[size];

return array;}

Page 35: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200935

Programming Demo

ArrayUtilsWrite a utility class with the following methods• printArray - A method that prints an array of ints

out to screen• swap - A method that takes in an array and two

indices a & b, whose locations in the array should be swapped

• sum – A method that sums all the elements in an array

Page 36: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200936

Programming Demo

Programming

Page 37: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200937

Testing ArrayUtils

Perform the following testsRead in a number of integers specified by the user into an array and: • Display the input entered by the user• Display the sum of all integers entered by the user• Swap the 1st and last elements of the array and

display the altered array

Page 38: COMP 110: Introduction to Programming Tyler Johnson Mar 25, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200938

Friday

Recitation

BringLaptops (fully charged)TextbookQuestions on Program 4


Recommended