Download presentation

Presentation is loading. Please wait.

Published bySara McMillan Modified over 3 years ago

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

2
COMP 110: Spring Announcements Lab 6 due tomorrow by midnight

3
COMP 110: Spring Questions?

4
COMP 110: Spring Today in COMP 110 Array Basics Programming Demo

5
COMP 110: Spring Array Basics Section 7.1 in text

6
COMP 110: Spring 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); }

7
COMP 110: Spring 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 scores We need to look at previous scores Lets simplify this first

8
COMP 110: Spring One Possibility… Assume exactly 5 scores System.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 scores if(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");

9
COMP 110: Spring 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 + score score23 + score24 + score ) / 80.0; System.out.println("Average score: " + average); // now do below/above average check for all 80 scores

10
COMP 110: Spring Arrays Theres 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

11
COMP 110: Spring 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 1 st integer in the array scores[1] //a single integer, the 2 nd integer in the array scores[2] scores[3] scores[4] //a single integer, the 5 th and last integer in the array

12
COMP 110: Spring 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

13
COMP 110: Spring 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 UNCisGreat

14
COMP 110: Spring 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]);

15
COMP 110: Spring Vector Example double[] vector = new double[3]; //an array of 3 doubles (x, y, z) vector[0] = 1.; //set the x value vector[1] = 56.; //set the y value vector[2] = 101.; //set the z value //compute the length of the vector double length = Math.sqrt(vector[0]*vector [0] + vector [1]*vector [1] + vector [2]*vector [2]); //normalize the vector double[] vectorN = new double[3]; vectorN[0] = vector[0]/length; vectorN[1] = vector[1]/length; vectorN[2] = vector[2]/length; (x,y,z)

16
COMP 110: Spring Arrays The array itself is referred to by a name scores or vector (in our examples) Indices the array scores scores[3]

17
COMP 110: Spring 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 0 for(int index = 0; index < 5; index++) scores[index] = 0; for(int index = 0; index < 5; index++) scores[index/2] = 0;

18
COMP 110: Spring Array Terminology scores[index/2] = 0; Array name Index Indexed Variable

19
COMP 110: Spring 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"); }

20
COMP 110: Spring 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 pressure pressure = new int[100]; //allocate memory for the array to hold 100 ints

21
COMP 110: Spring Array Details The base type can be any type double[] 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]

22
COMP 110: Spring 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];

23
COMP 110: Spring Use a Named Constant Why is it poor programming practice to use an int literal for the size? It can be error prone You 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;

24
COMP 110: Spring Determining the Length If youre 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];

25
COMP 110: Spring 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 array Pet[] pets = new Pet[20]; int sizeOfArray = pets.length; //sizeOfArray will have the value 20 You cannot change the value of length (it is final)

26
COMP 110: Spring 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 its not obvious where it comes from and its value may change!

27
COMP 110: Spring 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;

28
COMP 110: Spring 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

29
COMP 110: Spring 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!

30
COMP 110: Spring 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;

31
COMP 110: Spring 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] + " "); Output

32
COMP 110: Spring Arrays & Methods Arrays can be used with methods just like other objects can Arrays can be passed as arguments to methods Arrays 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

33
COMP 110: Spring Arrays as Arguments Example //init all array elements to 0 public void initArray(int[] array) { for(int i = 0; i < array.length; i++) array[i] = 0; }

34
COMP 110: Spring Returning Arrays Example //create an array of the given size and return it public int[] createArray(int size) { int[] array = new int[size]; return array; }

35
COMP 110: Spring Programming Demo ArrayUtils Write 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

36
COMP 110: Spring Programming Demo Programming

37
COMP 110: Spring Testing ArrayUtils Perform the following tests Read 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 1 st and last elements of the array and display the altered array

38
COMP 110: Spring Friday Recitation Bring Laptops (fully charged) Textbook Questions on Program 4

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google