Announcements Lab 6 was due today Lab 7 assigned this Friday

Slides:



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

Arrays I Savitch Chapter 6.1: Introduction to Arrays.
CS110 Programming Language I Lab 10: Arrays I Computer Science Department Spring 2014.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
CS0007: Introduction to Computer Programming Introduction to Arrays.
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Catie Welsh March 28,  Lab 7 due Friday, April 1st, 1pm 2.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Introduction to Collections Arrays. Collections Collections allow us to treat a group of values as one collective entity. The array is a collection of.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
Catie Welsh April 20,  Program 4 due Wed, April 27 th by 11:59pm  Final exam, comprehensive ◦ Friday, May 6th, 12pm  No class Friday - Holiday.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
8-1 Chapter-7 Part1 Introduction to Arrays –Array Types –Creating/Declaring Arrays –Initializing Arrays –Processing Array Contents –Passing Arrays as Arguments.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
COMP 110 Arrays Luv Kohli November 5, 2008 MWF 2-2:50 pm Sitterson 014.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Arrays Chapter 7.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Arrays.
Array in C# Array in C# RIHS Arshad Khan
Computer Organization and Design Pointers, Arrays and Strings in C
Review 1.
Michele Weigle - COMP 14 - Spr 04 Catie Welsh March 30, 2011
Arrays in Classes and Methods
Arrays 2/4 By Pius Nyaanga.
Chapter 7 Part 1 Edited by JJ Shepherd
New Structure Recall “average.cpp” program
Repetition-Counter control Loop
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
BIT115: Introduction to Programming
Arrays, For loop While loop Do while loop
CSS161: Fundamentals of Computing
Building Java Programs Chapter 7
Java Language Basics.
CS-161 Computer Programming Lecture 14: Arrays I
int [] scores = new int [10];
Java Programming Arrays
BIT115: Introduction to Programming
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Arrays ICS2O.
int [] scores = new int [10];
Building Java Programs
Arrays I Handling lists of data.
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
Arrays Arrays A few types Structures of related data items
Arrays.
Building Java Programs
Announcements Lab 3 was due today Assignment 2 due next Wednesday
Arrays, Part 1 of 2 Topics Definition of a Data Structure
How do you do the following?
Classes and Objects Object Creation
Week 7 - Monday CS 121.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Announcements Lab 6 was due today Lab 7 assigned this Friday Assignment 4 due next Friday

Questions? Last time: Method signatures

Today in COMP 110 Array Basics Programming Demo

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; } if (totalGames > 0) { double average = (double) scoreSum / (double) totalGames; System.out.println("Average score: " + average);

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 Let’s simplify this a little first

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");

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

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

Creating an Array int[] scores = new int[5]; This creates an array called “scores” that holds five integer values scores[0] scores[1] scores[2] scores[3] scores[4]

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

Indexing Where have we seen the word index before? String’s indexOf method Index numbers start with 0. They do NOT start with 1 or any other number.

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]);

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)

Arrays The array itself is referred to by a name “scores” or “vector” (in our examples) Indices 1 2 3 4 68 73 57 102 94 the array scores scores[3]

Indexing The index (value in square brackets) does not have to a simple integer It can be an 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 < 10; index++) scores[index/2] = 0;

Array Terminology scores[index/2] = 0; Indexed Variable Array name

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); 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");

Array Details Syntax for creating an array: Example: Alternatively: 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

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]

Use a Named Constant Use a named constant instead of an int literal when creating an array Good programming practice public static final int NUMBER_OF_READINGS = 100; int[] pressure = new int[NUMBER_OF_READINGS]; Poor programming practice int[] pressure = new int[100];

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;

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];

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)

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); 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!

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;

Be Careful with Indices Indices MUST be in bounds double[] entries = new double[5]; entries[5] = 3.7; //RUN-TIME ERROR! Index out of bounds Your code WILL compile with an out-of-bounds index But it will result in a run-time error (crash)

Crash if more than 10 scores are entered! 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!

Initializing Arrays You can initialize arrays when you declare them int[] scores = {68, 97, 102}; Equivalent to int[] scores = new scores[3]; scores[0] = 68; scores[1] = 97; scores[2] = 102;

Exercise What is the output? int[] anArray = new int[10]; for(int i = 0; i < anArray.length; i++) anArray[i] = 2*i; System.out.println(anArray[i] + " "); Output 0 2 4 6 8 10 12 14 16 18

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

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; }

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; }

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

Programming Demo Programming

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 Display each integer with its contribution to the sum Swap the 1st and last elements of the array and display the altered array

Friday Recitation Bring Laptops (fully charged) Questions on Program 4