The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.

Slides:



Advertisements
Similar presentations
Parameter passing mechanism: pass-by-reference. The Pass-by-reference mechanism - the agreement Recall: Parameter passing mechanism = agreement between.
Advertisements

Programming and Data Structure
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Kernighan/Ritchie: Kelley/Pohl:
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
Java Unit 9: Arrays Declaring and Processing Arrays.
03/16/ What is an Array?... An array is an object that stores list of items. Each slot of an array holds an individual element. Characteristics.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Floating point variables of different lengths. Trade-off: accuracy vs. memory space Recall that the computer can combine adjacent bytes in the RAM memory.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
“Introduction to Programming With Java” Lecture - 6 U MESH P ATIL
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
“Introduction to Programming With Java”
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
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.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
What does a computer program look like: a general overview.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Working with arrays (we will use an array of double as example)
Assignment statements using the same variable in LHS and RHS.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 CSC 201: Computer Programming I Lecture 2 B. S. Afolabi.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
The life time of local variables (in a method). Local variables Local variable: A local variable is used to store information that is relevant for the.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
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.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
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.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 7 User-Defined Methods.
Elementary Programming
Chapter 2 Elementary Programming
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 6 Arrays Solution Opening Problem
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
The method invocation mechanism and the System Stack
Lecture 18 Arrays and Pointer Arithmetic
Java Tutotrial for [NLP-AI] 2
Arrays .
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
Classes and Objects Object Creation
Presentation transcript:

The basics of the array data structure

Storing information Computer programs (and humans) cannot operate without information. Example: The array data structure is very suitable for storing a collection of similar data items CEO's of companies need sales information to make the correct decisions Computer programs (such as the min method) need input data to operate

The array data structure An array is a collection (multiple) of variables where: Each variable in the collection is of the same data type Note: that means that the size (number of bytes) of each variable is the same The variables are placed (stored) consecutively in memory

The array data structure (cont.) Example:

The array data structure (cont.) Properties of arrays: The array contains a fixed number elements Each array element is identified by an index length of the array = number of elements in the array You can specify the length when you create the array The first element of an array has the index 0

The array data structure (cont.) Because each variable is of the same size, if we know the location of the first element of an array, we can locate any other element of the array through its index Example: Suppose the first element is located at address 5000 Each array element is 4 bytes

The array data structure (cont.)

Then: Array element 0 is located at address 5000 Array element 1 is located at address 5004 Array element 2 is located at address Array element i is located at address ×i

Defining an array in Java In most programming languages, defining an array is a one-step process In Java, however, defining an array is a two-step process

Defining an array in Java (cont.) Defining an array in Java: Step 1: Define a variable to store the location of the first element of the array. This variable is called an (array) object reference variable (Recall that in Computer Science, a reference is an address of a variable or method)

Defining an array in Java (cont.) Step 2: Create the array and store the location of the first element of the array in the (array) object reference variable

Defining an array in Java (cont.) Example: Step 1: double[] a; // The type "double[]" is the // "array object reference" type // The variable a contains an address of // an array of doubles Step 2: a = new double[5] ; // new double[5] creates an array // of 5 elements of double type // new double[5] returns the address // of the first element of the array // which is stored in variable a

Defining an array in Java (cont.) Program example with array definition: witness the definition an array of 5 doubles in the previous example public class Avg2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double[] a; // Define an (array) object variable named "a" a = new double[5]; // new double[5]: create an array of 5 double variables // and returns the location of the first element double sum, avg; int i; // index

Defining an array in Java (cont.) for ( i = 0; i <= 4; i++ ) { System.out.print("Enter a number: "); a[i] = in.nextDouble(); // Read in number } /* Use the "running sum" algorithm to compute total */ sum = 0.0; for ( i = 0; i <= 4; i++ ) { sum = sum + a[i]; } avg = sum/5; System.out.println(avg); // Print average }

The data type double[] A double[] typed variable contains the address of the start of an array of double variables

The data type double[] (cont.) Example: Suppose we have an array of double variables in RAM memory: Suppose also that the address of the start of this array of double variables is address 5000

The data type double[] (cont.) Suppose we have defined the following variables: Situation: double[] a;

The data type double[] (cont.) The data type double[] allows us to store into the variable a the address of the start of the array (which is 5000):

The data type double[] (cont.) We can now use the reference (5000) stored in the variable a to locate the elements of the array !!!

The data type double[] (cont.) Note: A variable of the type double[] does not contain a double typed value Such variable contains a binary number that is used to access the computer RAM memory An address is completely different from a double typed value E.g., you would not perform a multiplication on the address it does not make any sense.

Other types of reference variables For every built-in data type of Java, there is a corresponding reference type Examples: double[] = a variable of this type contains an address of an array of double variables int[] = a variable of this type contains an address of an array of int variables boolean[] = a variable of this type contains an address of an array of boolean variables Etc.

Other types of reference variables (cont.) In fact, you can append "[ ]" to any data type. Note: It will change the meaning of the data type completely

The new operator We saw the usage of a new Java operator in the above example: a = new double[5] ;

The new operator (cont.) Syntax of the new operator: new ObjectType

The new operator (cont.) Notes: The data types other than the Java's built-in types are known as object types An array type in Java is an object type Warning: You must use an object type with the new operator The new operator cannot be applied to Java's built-in types (such as int, double, etc.)

The new operator (cont.) Effect of the new operator: It first creates (= reserve memory) a variable of the data type ObjectType The variable created by new operator will reside in the System Heap area (See: 8/mem-org.html)

The new operator (cont.) Then it return (just like in a method call) the address of the first allocated memory cell.

The new operator (cont.) We will illustrate the usage of the new operator by executing the above example program.

Illustration: definition of an array variable in Java Example program: array definition in Java (The enclosing class definition has been omitted for brevity)

Illustration: definition of an array variable in Java (cont.) What happens when we define an array in Java: The program execution begins with the main method:

Illustration: definition of an array variable in Java (cont.) When the execution reaches the definition double[] a;, the local variable a is created on the System Stack:

Illustration: definition of an array variable in Java (cont.) When the execution reaches the definition a = new double[5]; statement, the new operator will first create an array of 5 double variables in the System Heap:

Illustration: definition of an array variable in Java (cont.) Suppose that the address of the first element of the array is 5000 Then: The new operator returns the address of the first element of the array, which is 5000

Illustration: definition of an array variable in Java (cont.) The return value is subsequently used in the assignment statement:

Illustration: definition of an array variable in Java (cont.) So.... after processing the array definition instructions, we have the following:

Illustration: definition of an array variable in Java (cont.) The program can now access the array element through its local variable a !!!

Shorter forms of array definitions Previously, we have seen the 2 step array definition. Java allows you to write both step in one combine statement

Shorter forms of array definitions (cont.) Example: double[] a ; a = new double[5]; Can be written as: double[] a = new double[5];

Syntax of array definition in Java OK, after a length introduction, let's learn about the syntax to define an array in Java Syntax: defining an array Two steps: datatype[] variableName; // Define a reference variable variableName = new datatype[ EXPR ]; // Create array of length EXPR // Assign starting address to // variableName

Syntax of array definition in Java (cont.) One step: datatype[] variableName = new datatype[ EXPR ];

An alternate form of array definition The older programming language C uses the following syntax to define an array: double a[]; (instead of double[] a)

An alternate form of array definition (cont.) Since Java is derived from C++ and C++ is derived from C, the Java compiler will accept the following syntax to define array variables: Alternate syntax to define array variable in Java Two steps: datatype[] variableName; // Define a reference variable variableName = new datatype[ EXPR ]; // Create array of length EXPR // Assign starting address to // variableName

An alternate form of array definition (cont.) One step: datatype[] variableName = new datatype[ EXPR ];

An alternate form of array definition (cont.) Example: public class Avg3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double a[] = new double[5]; // Define an array of 5 elements double sum, avg; int i; // index for ( i = 0; i <= 4; i++ ) { System.out.print("Enter a number: "); a[i] = in.nextDouble(); // Read in number } }

An alternate form of array definition (cont.) /* Use the "running sum" algorithm to compute total */ sum = 0.0; for ( i = 0; i <= 4; i++ ) { sum = sum + a[i]; } avg = sum/5; System.out.println(avg); // Print average }

Initial values in the array elements When an array is first created, every element contains the initial value The initial value depends on the data type of the array elements

Initial values in the array elements (cont.) The initial value for each data type: Data typeInitial value A number type (e.g. int, double,...) 0 boolean false char the character NULL

Defining initialize array You can also specify your own initial values when you define an array. The syntax for defining an initialized array is: datatype[] variableName = { list of initial values } ;

Defining initialize array (cont.) Example: double[] a = { 3.0, 4.5, 6.7, 3.9, 9.0 } ;

Defining initialize array (cont.) Note: The length of the array is (automatically) determined by the number of values in the list. There is no 2 steps syntax to define an initialized array Very important: you do not (and cannot) use the new operator in the definition of an initialized array