Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Road Map Introduction to object oriented programming. Classes
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
18-Jun-15 Arrays. 2 A problem with simple variables One variable holds one value The value may change over time, but at any given time, a variable holds.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
CS 106 Introduction to Computer Science I 02 / 20 / 2008 Instructor: Michael Eckmann.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Introduction to Computers and Programming Class 21 Arrays Professor Avi Rosenfeld.
Computer Science I Arrays Professor: Evan Korth New York University.
 Pearson Education, Inc. All rights reserved Arrays.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
CS0007: Introduction to Computer Programming Introduction to Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
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: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Chapter 8: Arrays.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
BIT115: Introduction to Programming
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
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.
 2005 Pearson Education, Inc. All rights reserved Arrays.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
Lecture 5 array declaration and instantiation array reference
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
© 2016 Pearson Education, Ltd. All rights reserved.
Arrays, For loop While loop Do while loop
7 Arrays.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
EKT150 : Computer Programming
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Object Oriented Programming in java
BIT115: Introduction to Programming
MSIS 655 Advanced Business Applications Programming
Building Java Programs
Arrays in Java.
Arrays.
Presentation transcript:

Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University

Road Map What is an Array? Parts of an Array –Elements, Indexes, Subscripts, etc. Declaring Arrays Initializing Arrays Reading: –Liang 5: Chapter 5, Sections 5.1 – 5.2 (except 5.2.5)

What is an Array?

An array is a collection of variables. Arrays have three important properties: –arrays represent a group of related data (for example, temperature for the last five days, or stock prices for the last 30 days.) –all data within a single array must share the same data type (for example, you can create an array of ints or an array of floats, but you cannot mix and match ints with floats.) –The size of an array is fixed once it is created.

What exactly are we talking about?! Let’s say you have ten students and you want to save the grades for each of them for use throughout your program (i.e. we need to remember every grade not just loop and count them or average them, etc.) Could do it the hard way: Set up ten variables called studentOneGrade, studentTwoGrade, studentThreeGrade, etc. Very difficult to use and manipulate Instead, could use an array to do it the easy way…

Using an array variable Create an array variable called studentGrades[10] Declared as follows: int [] studentGrades = new int[10]; This sets up a location in memory for 10 integers which can be referenced using studentGrades[ # ] where # is the particular student you want to look at.

Array Naming Considerations The rules for naming variables apply when selecting array variable names –Composed of letter, digit, $ and underscore characters –Cannot start with a digit Follow all the good programming hints recommended for variable names –i.e. just think of it as an ordinary variable when making up the name

Parts of an Array

Parts of the array The array has some terminology we haven’t seen yet –Elements –Index (or Position Number) –Subscript –Zeroth element –Keyword “new”

Elements Refers to the individual items represented by the array. For example, –an array of 10 integers is said to have 10 elements –an array of 15 floats has 15 elements –an array of 5 characters has 5 elements –and so on…

Index (Position Number or Subscript) Refers to one particular element in the array Also known as position number or, more formally, as a subscript The first element in an array is represented by an index or subscript of 0 (zero). For example, –studentGrades[ 0 ] This first position is known as the zeroth element The second position is referred to by –studentGrades[ 1 ]

Figuring out the array positions In Java, an arrays’ elements start out at index 0 and go up to (the number of elements – 1) For example, our array of 10 student grades filled in with grades might look like: Value Index

Array positions (cont’d) We can access them by specifying the array name followed by square brackets with the index number between them. For example, System.out.println ("The third student’s grade is " + studentGrades[ 2 ] ); Would print only the third integer spot in the array (remember 0 is the first, 1 is the second, and 2 is the third element’s index / subscript) The output would look like the following: The third student’s grade is 99

Array positions (cont’d) The index scheme starting at 0 may be initially confusing. This is the cause of many off-by-one errors so study the concept carefully The element in the array’s first position is sometimes referred to as the zeroth element. Notice the difference between "position" and "element number"

subscript terminology From this point forward, for this class, all references to array elements will refer to the subscript of the array. In the event that we want to discuss the position of an element in an array, we will refer to it’s position. In other words, we will not use i'th element or element i notation unless we are referring to the zeroth element.

16 Keyword new The keyword new is used in Java when you wish to create a new object. In Java, arrays are objects. We will not speak about the details of an object. All you need to know is in the case of arrays, new is used to create the new array. All positions of the new array will automatically be initialized to the default value for the array’s type. –Numeric types: 0 –char \nul (0) –boolean false

Using Arrays

So how do we use arrays? Same concepts as other variables apply –Must declare the array –Must initialize the array (unlike regular variables, Java will initialize arrays with default values) Arrays variables are actually reference variables. –Can use arrays in expressions and methods, setting elements’ values or using their values, similar to the use of ordinary variables

Declaring an array First you can declare an array reference variable (you must specify the type of the elements in the array) : –int [] myFirstArray;//declares an array //variable for ints –Note: the line above does not allocate memory for the array (it cannot since we have not said the size of the array yet). It only sets aside enough memory to reference the array. Until we create an array, the reference is to null. Next, we create the array and “point” the reference to it: –myFirstArray = new int [10]; –To create the array, we need the number of elements in the array so the computer can set aside adequate memory for the array. We can combine the declaration and allocation lines into one line as follows: –int [] myFirstArray = new int [10];

20 Declaring arrays (cont) You can use a constant to set the size of the array final int GRID_ROWS_MAX 8; int [] gridRows = new int [ GRID_ROWS_MAX ];

Initializing an Array You can initialize an array when you declare it, as you do with other variables Syntax is slightly different, as you are now initializing more than one element at a time One way at declaration, using initializers: int myFirstArray[ ] = { 1, 1, 1, 1, 1 }; Note the braces around the initial zeroes which themselves are separated by commas. Also note that creating arrays in this way eliminates the need for the keyword new.

Initializing array with a for loop After declaring an array, you can initialize it in the body of your program by using a for loop: int [] myFirstArray = new int [ 5 ]; for (int i = 0 ; i <= 4 ; i++ ) { myFirstArray[ i ] = 1 ; } // end for Note the upper bound is 4, not 5! That is, you loop through 0 to 4 to initialize an array with 5 elements Note: Array elements are initialized with default values. Numeric types get 0, boolean get false and char gets the null character (ascii code 0).

Some powerful features of arrays Can set array elements equal to other values or expressions. For example, studentGrades[ 1 ] = 100 ; This would set the array element with a subscript of 1 to a grade of 100. That is, the second student would have a grade of 100. Java allows us to access an array’s length by using the following notation: –studentGrades.length would evaluate to 10

powerful features (cont) Can use expressions as the subscript –E.g. if variables a = 1 and b = 2 studentGrades[ a + b ] would be the same as writing studentGrades[ 3 ] Can use array elements in expressions –E.g. int gradeTotal = 0 ; gradeTotal = studentGrades[ 0 ] + studentGrades[ 1 ] + studentGrades[ 2 ] + …etc… studentGrades[ 9 ] ; –Would add up all the array elements and store them in gradeTotal.

25 Powerful features in Java (cont) In java, you do not need to know the size of the array at COMPILE time. Instead you can know the size at RUN time. For example, the following is legal: inputString = JOptionPane.showInputDialog ("How many students ?"); int students = Integer.parseInt (inputString); int [] myFirstArray = new int [students];

Accessing elements with for loop Can use a for loop to print the contents of an array int [] myFirstArray = new int [ 5 ]; for (int i = 0 ; i <= myFirstArray.length – 1; i++ ) { System.out.println ("array element " + i + " is equal to " + myFirstArray [i]); } // end for Note the use of myFirstArray.length instead of using the size itself. It is better style to do so. Why?

Array Bounds Very Important: Java does not provide array bounds checking at compile time. This means that your program will crash at run time of you try to access memory outside of an array’s bounds. For example, suppose you have: int [] myFirstArray = new int [ 10 ]; myFirstArray [100] = 45; 100 is very far outside your defined size (0..9) However, the compiler will not indicate an error.