Arrays, Collections and Repetition Part A – Arrays and Repetition

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Road Map Introduction to object oriented programming. Classes
© The McGraw-Hill Companies, 2006 Chapter 5 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.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
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 Set 9 Arrays, Collections and Repetition Part C - Random Numbers Rectangular and Jagged arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.
Arrays Adapted from materials created by Dr. Donald Bell, Cal Poly 2000 (updated February 2004)
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Arrays 1.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Arrays Chapter 7.
An Introduction to Programming with C++ Sixth Edition
Computer Programming BCT 1113
IS 350 Arrays.
© 2016 Pearson Education, Ltd. All rights reserved.
Array, Strings and Vectors
2. Understanding VB Variables
JavaScript: Functions.
Java Review: Reference Types
Lecture Set 4 Data Types and Variables
Data Structures and Abstract Data Types
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Arrays, For loop While loop Do while loop
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Starting JavaProgramming
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
Java Programming Arrays
Arrays in Java What, why and how Copyright Curt Hill.
Introduction To Programming Information Technology , 1’st Semester
Object Oriented Programming in java
Lecture Set 9 Arrays, Collections and Repetition
MSIS 655 Advanced Business Applications Programming
Arrays.
Arrays Chapter 7.
CISC181 Introduction to Computer Science Dr
CIS16 Application Development and Programming using Visual Basic.net
7 Arrays.
Introduction to Data Structure
Java Programming Language
Data Structures & Algorithms
Visual Programming COMP-315
Java: Variables, Input and Arrays
Introduction to Computer Programming IT-104
Arrays.
SPL – PS2 C++ Memory Handling.
Lecture Set 9 Arrays, Collections, and Repetition
Presentation transcript:

Arrays, Collections and Repetition Part A – Arrays and Repetition Lecture Set 9 Arrays, Collections and Repetition Part A – Arrays and Repetition

Objectives Understand and work with arrays Particularly – what’s unique about C# arrays Really – not much compared to Java arrays More on do loops, while loops and for loops to examine array elements Much of this should be review – after two semesters of Java it should be easy reading 11/9/2018 4:17 PM

Recap: Where We Have Been and Look Ahead: Where We are Headed We have now seen and used a number of C# .NET programming tools Tools designed to help us structure processes as well as data Repetition structures Decision structures Exception handling (try-catch) structures 11/9/2018 4:17 PM

Recap & Look Ahead (continued - 1) Data All the built-in data types int, double, char, etc Some structured data Strings, streams, graphing surfaces, collections, data bases (yet to come), forms, other controls These are all MODELS of problem space entities which carry with them data stores (attributes) and operations (methods) on these stores In C# we have used classes in building these models The models are all descendant from the object class 11/9/2018 4:17 PM

Recap & Look Ahead (continued - 2) In this Lecture Set (9), we take a closer (mostly review) look at two kinds of related collection data structures Arrays (and their variants) Lists We will then move on (in later lecture sets) to take a more thorough look at classes and inheritance and software development using classes as the basic design component 11/9/2018 4:17 PM

Do we need all these structures? NO! We can program without any of them, and some people do However, they do help regularize procedural (logic) control and data patterns which programmers have repeatedly used for decades It is widely believed that the use of these patterns is helpful in all phases of the development of computer software, including design, programming and testing, debugging, maintenance, etc And so, we move ahead toward gaining some degree of mastery in understanding and using these patterns 11/9/2018 4:17 PM

Objectives – Introduction to Arrays Here we introduce the concept of an array We will see how to declare arrays and how to reference (access) the elements of an array We will also gain some insights as to how arrays are stored This may come as a bit of a surprise Arrays are reference variables (from the array class) The named variable contains a reference to the base elements of an array, all of which are stored in the heap (illustrated in a later slide) NOTE: Some of the memory allocation pictures that follow relate to VB but the translation to C# should be relatively easy 11/9/2018 4:17 PM

Characteristics of Arrays An array stores multiple data items The elements of an array must have the same data type – called the base type Or the elements must be of a type derived from the base type An array can store a list of primary data types or other data types An array of integers or text boxes, for example An array has one or more dimensions A one-dimensional array can be thought of as a list A two-dimensional array can be thought of as a grid or table (or a “rectangular array”) A C# array can have between 1 and 60 dimensions 11/9/2018 4:17 PM

Characteristics of Arrays (Declarations) The number of dimensions in an array is called the rank A one-dimensional array has a rank of 1 A two-dimensional array has a rank of 2 Each data item stored in an array is called an element If a size is not specified no elements are allocated Examples: int [] table; // Declares an integer array of unspecified size decimal [0] oneElementArray; // A 1-dimension array of one decimal element char [] singleArray = new float[4]; // A 1-dimension array of five float data // The valid subscripts for this array are [0] through [3]. int [,] table; // Two-d array of unspecified size float [9, 9] table; int SalesArray[,] = { {150, 140, 135, 110}, {155, 148, 082, 90}, {162, 153, 191, 140}, {181, 176, 191, 184} ]; 11/9/2018 4:17 PM

Characteristics of Arrays (Referencing elements) An array element is referenced by a unique index value called a subscript One subscript is used to reference elements in a one-dimensional array Example: Two subscripts are used to reference elements in a two-dimensional array 11/9/2018 4:17 PM

The Array Class (Members) The Length property gets the number of elements in the array The Length property is 1-based The Rank property gets the number of dimensions A one-dimensional array has a Rank of 1 The GetLength method gets the number of array elements in a particular dimension The GetUpperBound and GetLowerBound methods get the largest and smallest subscript for a dimension These methods are 0-based The array dimension is passed as an argument The Sort method sorts an array – an entire array ONLY 11/9/2018 4:17 PM

Common Array Tasks Arrays must be declared just as any variable must be declared It is possible to declare and initialize an array in the same statement It's possible to determine the bounds of an array Array size is fixed and cannot be changed at run time (but list sizes are not fixed) Arrays are manipulated element by element – we do not have the ability to manipulate whole arrays other than element by element 11/9/2018 4:17 PM

Declaring Arrays (Syntax) [public | internal | private | protected] dataType [[size]] arrayName = initExpr The access modifier (public, private, internal, protected) defines the array's visibility The identifier (name) is defined by arrayName The optional size contains the value of the largest subscript The size argument is 0-based dataType defines the data type of the array initExpr is used to assign initial values to the array's elements 11/9/2018 4:17 PM

Implementation of Arrays The Array class is a reference type Thus, any array variable stores the memory address of the actual array The actual array is allocated in the “heap”  An array variable (a reference variable) declared without a size specification int x(); has a value of null 11/9/2018 4:17 PM

How Memory is Allocated to an Array (VB) 11/9/2018 4:17 PM

Initializing an Array An array can be initialized when it is declared The initialization list appears in braces ({}) A comma separates each initialization value The array must be dynamic (declared without an initial subscript value) Example to declare and initialize an Integer array with four elements and valid subscripts of 0 .. 3: int integerArray() = {24, 12, 34, 42}; 11/9/2018 4:17 PM

Declaring and Initializing an Array (VB) 11/9/2018 4:17 PM

Declaring and Initializing Boolean and String Arrays Declare and initialize a Boolean array Boolean [] WeekDayArray = {false, false, true, true, true, true, true}; Declare and initialize a String array String [] MonthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 11/9/2018 4:17 PM

Determining an Array's Bounds The GetUpperBound method gets the largest subscript for a particular dimension It returns the largest subscript, not the number of elements The GetLowerBound method gets the smallest subscript for a particular dimension The 0-based dimension is passed as an argument to each method The method will throw an exception if the array dimension does not exist 11/9/2018 4:17 PM

Determining an Array's Bounds (Examples) Get the lower and upper bound of the first array dimension for the array named MonthNames int smallestSubscript, largestSubscript; smallestSubscript = MonthNames.GetLowerBound(0); // Result = 0 largestSubscript = MonthNames.GetUpperBound(0); // Result = 12 11/9/2018 4:17 PM

Re-Using an Array An array's size is determined by the number of dimensions in the array and the number of elements in each dimension An array in C# cannot be re-dimensioned in the same sense as is possible in VB, but it can be “reused” via re-declaration This causes the existing array to be destroyed and a new one to be created (as per strings) Data in the original is not saved If the size of an array cannot be determined at execution time, you should use a List or perhaps a non-linear structure (tree, graph, etc) 11/9/2018 4:17 PM

Performing Assignment Statements with Arrays Assignment statements using arrays require a subscript The subscript appears in parentheses after the array name The data types of the left and right side of the assignment statement must be compatible 11/9/2018 4:17 PM

Assignment Statements with Arrays (Example) Declare an array with 12 elements (subscript values from 0 to 11) double [12] SalesList; Store and retrieve a value from the second array element (a subscript value of 1) Sales[1] = 84616.12; double SalesListItem = SalesList[1]; 11/9/2018 4:17 PM

Storing and Retrieving Array Values (VB) 11/9/2018 4:17 PM

Understanding Arrays of Different Types (VB) - 1 (optional) We begin by looking at some code  This code illustrates the formation of arrays of objects (the parent data type of all other types in C#) as well as arrays of integers, and user-defined classes Integers, other built-in types and user-defined types are all classes derived from the object class We can therefore store objects of any of these types in a array of objects 11/9/2018 4:17 PM

Arrays of Different Type Data (VB) – 2 (optional) 11/9/2018 4:17 PM

Arrays of Different Types of Data – 3 (VB) (optional) There are some important things to note in this code 1. aStruct and aClass are defined elsewhere 2. The methods discussed earlier on arrays of a single type still work the same here for generic arrays Recall that there was an issue of what happens when primitive types are inserted into a list. There is no such issue for arrays UNLESS we have created an array of type object or any type derived from object 11/9/2018 4:17 PM

Arrays of Different Types of Data – 4 (VB) (optional) Arrays of reference type variables contain elements that are references to their actual elements which are stored in the heap

Arrays of Different Types of Data – 5 (optional) Note that primitive types are stored in an array of base type object must be boxed and described in an earlier lecture set In other words, if it becomes necessary to store data of a primitive type “as an object” we must first convert the data from the primitive type to the object type and THEN store it 11/9/2018 4:17 PM

Variables and Array Subscripts Variables are often used as array subscripts Especially when using loops to examine all the elements in an array Variables used as subscripts must have an integral data type 11/9/2018 4:17 PM

Variables and Array Subscripts (Example) Reference an array element with a variable as a subscript: int SubscriptValue = 1; double SalesListItem; SalesListItem = SalesList[SubscriptValue]; 11/9/2018 4:17 PM

Using Loops to Examine Array Elements Common array tasks involving loops Calculate the total value of all array elements using an accumulator Calculate the minimum value stored in an array Calculate the maximum value stored in an array Calculate the average value of the elements in an array 11/9/2018 4:17 PM

Using a Loop to Examine Array Elements (VB) 11/9/2018 4:17 PM

Examine an Array's Elements (Example) Tally the values of an array's elements. Total contains the total value double total = 0.0; int counter = 1; while (counter <= salesList.GetUpperBound(0)) { Total += salesList[Counter]; counter++; } // end while loop 11/9/2018 4:17 PM

Common Array Errors Errors are commonly made when processing arrays Forgetting to include a subscript int [12] DemoArray; DemoArray = 100; Subscript out of range errors int [10] DemoArray; DemoArray[20] = 100; DemoArray[–1] = 100; 11/9/2018 4:17 PM

Common Array Errors (continued) Forgetting to examine the first or last array element int [12] demoArray; double total; for (int cntr = 1; cntr <= demoArray.GetUpperBound(0); cntr++) { total += demoArray(cntr) } // end for 11/9/2018 4:17 PM