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.

Slides:



Advertisements
Similar presentations
Chapter 8: Arrays.
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
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.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Numbers and Arrays. Widening and narrowing Numeric types are arranged in a continuum: double float long int short byte, char You can easily assign a narrower.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
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.
26-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.
PHYS 2020 Making Choices; Arrays. Arrays  An array is very much like a matrix.  In the C language, an array is a collection of variables, all of the.
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.
Chapter 9 Introduction to Arrays
CS1061 C Programmuing Lecture 12 Arrays A. O’Riordan, 2004.
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.
Java Unit 9: Arrays Declaring and Processing 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.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
CPS120: Introduction to Computer Science Arrays. Arrays: A Definition A list of variables accessed using a single identifier May be of any data type Can.
11 Finding Winners Using Arrays Session 8.2. Session Overview  Find out how the C# language makes it easy to create an array that contains multiple values.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
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.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 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.
Pemrograman Dasar Arrays PTIIK - UB. Arrays  An array is a container object that holds a fixed number of values of a single type.  The length of an.
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.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
CPS120: Introduction to Computer Science Lecture 15 Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Arrays Chapter 13 How to do the following with a one dimensional array: Declare it, use an index.
Lecture 3 Introduction to Computer Programming CUIT A.M. Gamundani Presentation Layout from Lecture 1 Background.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Arrays Version 1.1. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Agenda Comments Identifiers Keywords Syntax and Symentics Indentation Variables Datatype Operator.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Two Dimensional Arrays. Students will be able to: code algorithms to solve two- dimensional array problems. use 2-D arrays in programs. pass two-use 2-D.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
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.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
27-Jun-16 Arrays. 2 Multiple values An array lets you associate one name with a fixed (but possibly large) number of values Arrays are like Python’s lists,
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
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.
Arrays 6-Dec-18.
Arrays 2-May-19.
Arrays.
Presentation transcript:

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 value If you want to keep track of many values, you need many variables All of these variables need to have names What if you need to keep track of hundreds or thousands of values?

Multiple values An array lets you associate one name with a fixed (but possibly large) number of values All values must have the same type The values are distinguished by a numerical index between 0 and array size minus myArray

Indexing into arrays To reference a single array element, use array- name [ index ] Indexed elements can be used just like simple variables –You can access their values –You can modify their values An array index is sometimes called a subscript

Using array elements Examples: x = myArray[1];// sets x to 43 myArray[4] = 99;// replaces 14 with 99 m = 5; y = myArray[m];// sets y to -57 z = myArray[myArray[9]];// sets z to myArray

Array values An array may hold any type of value, but... –all values in an array must be the same type, and... –you must specify that type when you declare the array For example, you can have: –an array of int (integers) –an array of Strings ( String is a built-in class) –an array of Person (if Person is a class you have defined) –an array of arrays of Strings

Strings and arrays Strings and arrays both have special syntax Strings are objects, and can be used as objects Arrays are objects, but –Arrays are created using special syntax: new type [ size ] instead of new Person() –If an array holds elements of type T, then the array’s type is “array of T ”

Two ways to declare arrays You can declare more than one array variable in the same declaration: int a[ ], b, c[ ], d; // notice position of brackets a and c are int arrays b and d are just int s Another syntax: int[ ] a, b, c, d; // notice position of brackets a, b, c and d are int arrays –When the brackets come before the first variable, they apply to all variables in the list –This is the preferred syntax, because the type, int[ ], is written together in one place

Important jargon When you declare an array variable (for example, int[ ] scores; ) you are saying what kind of array the variable can hold, but you haven’t actually created the array –Analogy: it’s like creating a new position in a company, but not yet having hired someone to fill that position You create an array with the new operator, for example, new int[25] You define the variable by assigning an actual value to it, for example, scores = new int[25]; You can combine declaration and definition in a single statement, for example, int[ ] scores = new int[25];

An array’s size is not part of its type When you declare an array, you declare its type; you must not specify its size –Example: String names[ ]; When you create the array, you allocate space; you must specify its size –Example: names = new String[50]; This is true even when the two are combined –Example: String names[ ] = new String[50];

Array assignment When you assign an array value to an array variable, the types must be compatible The following is not legal: double dub[ ] = new int[10]; // illegal The following is legal: int myArray[ ] = new int[10]; –...and later in the program, myArray = new int[500]; // legal! –Legal because array size is not part of its type

Example of array use I Suppose you want to find the largest value in an array scores of 10 integers: int largestScore = 0; for (int i = 0; i < 10; i++) { if (scores[i] > largestScore) { largestScore = scores[i]; } } By the way, do you see an error in the above program? –What if all values in the array are negative?

Example of array use II To find the largest value in an array scores of 10 (possibly negative) integers: int largestScore = scores[0]; for (int i = 1; i < 10; i++) { if (scores[i] > largestScore) { largestScore = scores[i]; } }

Example of array use III Suppose you want to find the largest value in an array scores and the location in which you found that value: int largestScore = scores[0]; int index = 0; for (int i = 1; i < 10; i++) { if (scores[i] > largestScore) { largestScore = scores[i]; index = i; } }

Variable names Use the following style rules for variable names: –Use nouns to name variables: total, size, position –Start with a lowercase letter: result, not Result –Capitalize the first letter of each additional word in a multiword name: sumOfDigits, dateOfLastEntry, totalValue –Don’t use underscores: sumOfDigits, not sum_of_digits –Capitalize no more than the first letter of acronyms: lastUrl, not lastURL ; asciiValue, not ASCIIValue –Don’t abbreviate: sumOfDigits, not sumDig ; employees, not emps Array names should be plural nouns: scores, employees checkbookEntries, vectorComponents –This is particularly true when the individual entries have meaning independent of one another –Exception: When only the entire collection has meaning: forceVector, matrix, pascalsTriangle

Length of an array Arrays are objects Every array has an instance constant, length, that tells how large the array is Example: for (int i = 0; i < scores.length; i++) { System.out.println(scores[i]); } Use of length is always preferred over using a constant such as 10

Magic numbers Use names instead of numbers in your code –Names help document the code; numbers don’t –It may be hard to tell why a particular number is used-- we call it a magic number This is a pejorative term –You might change your name about the value of a “constant” (say, more than ten scores ) You can change the value of a name in one place –An array’s length is always correct!

Initializing arrays I Here’s one way to initialize an array of objects Person people[] = new Person[20]; for (int i = 0; i < people.length; i++) { people[i] = new Person("John"); } This approach has a slight drawback: all the array elements have similar values

Initializing arrays II There is a special syntax for giving initial values to the elements of arrays –This syntax can be used in place of new type [ size ] –It can only be used in an array declaration –The syntax is: { value, value,..., value } Examples: int primes[ ] = {2, 3, 5, 7, 11, 13, 19}; String languages[ ] = { "Java", "C", "C++" };

Array literals A literal is a value that you write directly in the code –Examples: "This is a string" You can create an array literal with the following syntax: type [ ] { value1, value2,..., valueN } Examples: myPrintArray(new int[] {2, 3, 5, 7, 11}); int foo[ ]; foo = new int[ ] {42, 83};

Arrays of arrays The elements of an array can be arrays Once again, there is a special syntax Declaration: int table[ ] [ ]; Definition: table = new int[10][15]; Combined: int table[ ] [ ] = new int[10][15]; The first index ( 10 ) is usually called the row index; the second index ( 15 ) is the column index An array like this is called a two-dimensional array

Example array of arrays int table[ ][ ] = new int[3][2]; or, int table[ ][ ] = { {1, 2}, {3, 6}, {7, 8} }; For example, table[1][1] contains 6 table[2][1] contains 8, and table[1][2] is “array out of bounds” To “zero out this table”: for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { table[i][j] = 0; } } How could this code be improved?

Size of 2D arrays int table[ ][ ] = new int[3][2]; The length of this array is the number of rows: table.length is 3 Each row contains an array To get the number of columns, pick a row and ask for its length: table[0].length is 2 But remember, rows may not all be the same length

The End