McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 8 Arrays.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Programming Logic and Design Sixth Edition
Arrays. INTRODUCTION TO ARRAYS Just as with loops and conditions, arrays are a common programming construct and an important concept Arrays can be found.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 14 – Student Grades Application: Introducing.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
Chapter 8 Arrays and Collections Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
 Pearson Education, Inc. All rights reserved Arrays.
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.
Processing Arrays Lesson 8 McManusCOP Overview One-Dimensional Arrays –Entering Data into an Array –Printing an Array –Accumulating the elements.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Interest Calculator Application Introducing the For...Next Repetition Statements.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Chapter 8 Arrays and Strings
Copyright © 2001 by Wiley. All rights reserved. Chapter 5: The Repetition Process in Visual Basic Event Driven Loops Determinate Loops Indeterminate Loops.
Array Processing.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
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.
 2005 Pearson Education, Inc. All rights reserved. 1 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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
8-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Arrays Chapter 8.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 18 – Student Grades Application Introducing.
6-1 Chapter 6 Working with Arrays in VB.NET. 6-2 Learning Objectives Understand the use of list and table arrays in VB.NET projects and the difference.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Arrays, Timers, and More 8.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Processing Arrays Lesson 9 McManusCOP Overview One-Dimensional Arrays –Entering Data into an Array –Printing an Array –Accumulating the elements.
7-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Programming with Microsoft Visual Basic 2012 Chapter 9: Arrays.
Arrays An array is a list or series of values all referenced by the same name Also referred to as a table An element is an individual item in the array.
An Introduction to Programming with C++ Sixth Edition Chapter 12 Two-Dimensional Arrays.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
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.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 8 Arrays Brief description on how to navigate within this presentation (PPT) The first time a Key Term from the chapter is used in the PPT, it.
Chapter 6: Using Arrays.
© 2016 Pearson Education, Ltd. All rights reserved.
CHAPTER FIVE Decision Structures.
Arrays, For loop While loop Do while loop
Brief description on how to navigate within this presentation (ppt)
Arrays.
Programming Logic and Design Fifth Edition, Comprehensive
Programming In Visual Basic .NET
Presentation transcript:

McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 8 Arrays

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-2 Chapter Objectives Establish an array and refer to individual elements in the array with subscripts Use a foreach loop to traverse the elements of an array Create a structure for multiple fields of related data Accumulate totals using arrays Distinguish between direct access and indirect access of a table Write a table lookup for matching an array element Combine the advantages of list box controls with arrays Store and look up data in multidimensional arrays

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-3 Single-Dimension Arrays A list or series of values similar to a list of values for list boxes and combo boxes—without the box Use an array to store a series of variables for later processing May be referred to as tables or subscripted (or indexed) variables Individual variables (elements) are treated the same as any other variable and may be used in any statement

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-4 Subscripts Advantage of an array is using variables for subscripts in place of constants Subscripts are constants, variables, or numeric expressions Must be integers Array name and number of elements are declared –No limit to the number of elements (except for available memory)

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-5 The Declaration Statement for Arrays – General Form - 1 Declare arrays as public or private –Defaults to private Location of declaration determines scope and lifetime of array variables Declare an array by placing opening and closing square brackets after the data type Declare the number of elements or the initial values of array elements (which determine the number of elements)

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-6 The Declaration Statement for Arrays – General Form - 2 Datatype[] arrayName = new Datatype[NumberOfElements]; Datatype[] arrayName = new Datatype[] {InitialValueList}; Datatype[] arrayName = {InitialValueList}; [public|private] Datatype[] arrayName = new Datatype[NumberOfElements];

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-7 The Declaration Statement for Arrays – Examples Array subscripts are zero based –First element is always element zero All array elements must be the same data type string[] nameString = new string[25]; decimal[] balanceDecimal = new decimal[10]; int[] numbersInteger = new int[] {1, 5, 12, 18, 20}; string[] departmentsString = new string[] {"Accounting", "Marketing", "Human Relations"}; private string[] categoryString = new string[10]; public string[] IDNumbersString = new string[5]; string[] nameString = {"Sean", "Sam", "Sally", "Sara"};

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-8 Valid Subscripts A subscript must reference a valid element of an array –Zero through one less than the number of elements C# rounds fractional subscripts C# throws an exception for a subscript that is out of range Arrays are based on the System.Array collection

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-9 foreach Loops - 1 To reference each element of an array use for loops or foreach loops Advantages of a foreach loop –The subscripts of the array do not have to be manipulated –How many elements there are in an array does not have to be known Array elements are read-only in the body of a foreach loop C# automatically references each element of the array and assigns its value to ElementName –Makes one pass through the loop per element –The variable used for ElementName must be the same data type as array elements or an Object data type

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved foreach Loops - 2 Best to declare the variable for ElementName as part of the foreach statement to create a block- level variable A foreach loop will execute if the array has at least one element Loop continues to execute until all elements are processed Execution of code continues with the line following the closing braces when the loop finishes You can use a break statement to exit the loop early

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved foreach Loops - 3 General Form Examples foreach (DataType ElementName in ArrayName) { // Statement(s) in the loop. } foreach (string oneNameString in nameString) { Console.WriteLine(oneNameString); // Write one element of the array. } foreach (decimal oneItemDecimal in allItemsDecimal) // Display all elements in the array. { totalsRichTextBox.Text += indexInteger++ + "\t" + totalDecimal.ToString() + "\n"; }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Structures Combine multiple fields of data to create a new structure using the struct statement –Similar to defining a new data type struct declaration –Cannot go inside a method –Generally placed at the top of a file with the class- level declarations –Can be placed outside of a class –Public by default; can declare as private –The number of elements of an array inside a structure cannot be specified

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The struct Statement - Examples struct Employee { public string lastNameString; public string firstNameString; public string SSNString; public string streetString; public string stateString; public string ZIPString; public DateTime hireDateTime; public int payCodeInteger; } public struct Product { public string descriptionString; public string IDString; public int quantityInteger; public decimal priceDecimal; } struct SalesDetail { public decimal[] saleDecimal; }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Declaring Variables Based on a Structure After you declare a structure, declare variables of the structure, just as if it were a data type –The location of the variable declaration determines the scope and lifetime of the variable Employee officeEmployee; Employee warehouseEmployee; Product widgetProduct; Product inventoryProduct[] = new Product[100]; SalesDetail housewaresSalesDetail; SalesDetail homeFurnishingsSalesDetail;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Accessing the Elements in a Structure Variable - 1 Each field of data in a structure is referred to as an element To access elements, use the dot notation similar to that used for objects A variable that is not an array does not need an index A variable that is an array needs the item and the element within the array of structures specified

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Accessing the Elements in a Structure Variable - 2 Examples officeEmployee.lastNameString officeEmployee.hireDateTime warehouseEmployee.lastNameString widgetProduct.descriptionString widgetProduct.quantityInteger widgetProduct.priceDecimal inventoryProduct[indexInteger].descriptionString inventoryProduct[indexInteger].quantityInteger inventoryProduct[indexInteger].priceDecimal

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Including an Array in a Structure An array can be included in a structure, but you cannot specify the number of elements in the struct declaration Public struct SalesDetail //Class-level declarations. { public decimal[] saleDecimal; } At the class level or inside a method, declare the name of the variable SalesDetail housewaresSalesDetail; Inside a method establish the number of elements in the array housewaresSalesDetail.saleDecimal = new decimal[7]; In processing, use a subscript to refer to each individual element within the structure housewaresSalesDetail.saleDecimal[dayIndexInteger] = todaysSalesDecimal;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Using Array Elements for Accumulators Array elements are regular variables –Perform the same way as all variables used so far –Can be used for counters or total accumulators Eight totals will be accumulated to demonstrate the use of array elements as total accumulators

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Adding to the Correct Total Use the totalDecimal array to hold the sales totals for eight scout troops –User enters the group number and sales –Subtract one from the group number and use it as a subscript for the correct total –Add the sales amount to the corresponding total –This technique is called direct reference of the array // Convert input group number to subscript. groupNumberInteger = int.Parse(groupTextBox.Text) – 1; // Add sale to the correct total. saleDecimal = decimal.Parse(saleTextBox.Text); totalDecimal[groupNumberInteger] += saleDecimal;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Debugging Array Programs - 1 View array elements in debugging time by setting a breakpoint in code and viewing the Autos or Locals window –Click the plus sign to the left of the array name to view the individual array elements

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Debugging Array Programs - 2 Visual Studio 2008 introduces visualizers –Pop up the value of an array in the Code Editor window Pause the mouse pointer over a variable or array Array name pops up, point to plus sign to display current contents of each element

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Table Lookup - 1 Values used to identify a series of elements may not be sequential –Establish a structure and declare an array of the structure –In the Form_Load event handler, initialize the array elements –Use a table lookup to find the correct array element, the subscript –Compare the input group number to each element in the table, one by one –When a match is found, add to the corresponding total

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Table Lookup - 2 public struct GroupInfo { public string groupNumberString; public decimal totalDecimal; } public GroupInfo[] arrayGroup = new GroupInfo[8]; groupNumber -String totalDecimal [0] [1] [2] [3] [4] [5] [6] [7] indexInteger 2

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Table Lookup - 3 UML action diagram of the logic of a lookup operation

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Coding a Table Lookup - 1 do loop works better than a foreach loop –Logic of a lookup operation // Convert input group number to a subscript. do { if (groupTextBox.Text == arrayGroup[groupNumberInteger].groupNumberString) { // A match is found. decimal saleDecimal = decimal.Parse(salesTextBox.Text); arrayGroup[groupNumberInteger].totalDecimal += saleDecimal; foundBoolean = true; // Clear the controls. groupTextBox.Clear(); salesTextBox.Clear(); groupTextBox.Focus(); } groupNumberInteger++; } while (groupNumberInteger < 8 && !foundBoolean);

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Coding a Table Lookup - 2 Validate group number entry –If wrong, display a message box Check foundBoolean after loop completes to determine why loop terminated –Did it terminate because of a match or without a match Table lookup works for any table, numeric or string Searched fields do not have to be in any sequence

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Using List Boxes with Arrays Use a list box or combo box rather than a text box for user input Use the list's SelectedIndex property to determine the array subscript –SelectedIndex property holds the position of the selected list item groupNumberInteger = groupComboBox.SelectedIndex;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Multidimensional Arrays - 1 To define a two-dimensional array or table: –The declaration statement specifies the number of rows and columns The row is horizontal and the column is vertical –Specify the number of elements within parentheses and/or specify initial values –Specify the row with the first subscript and the column with the second subscript Use a comma between the subscripts –Always use two subscripts when referring to individual elements of the table

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Multidimensional Arrays - 2 Elements of an array are used the same way as other variables –Accumulators, counts, reference fields for lookup –In statements –As conditions Invalid references would include a value greater than the subscript for the row or column

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Multidimensional Arrays - 3 General form Examples –Both of these statements create arrays with 3 rows and 4 columns –Note the comma between square brackets Specifies that the array has two dimensions DataType[,] ArrayName = new DataType[NumberOfElements, NumberOfColumns]; DataType[,] ArrayName = new DataType[,] = {ListOfValues}; string[,] nameString = new string[3, 4]; string[,] nameString = new string[,] = { {"James", "Mary", "Sammie", "Sean"}, {"Tom", "Lee", "Leon", "Larry"}, {"Maria", "Margaret", "Jill", "John"} };

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Initializing Two-Dimensional Arrays Numeric array elements are initially set to zero String elements are initially set to an empty string You may need to initialize (or reinitialize) arrays to some other value –Nested for loops can set each array element to an initial value Cannot use a foreach loop to initialize an array

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Nested for Loop Example for (int rowInteger = 0; rowInteger < 3; rowInteger ++ ) { for (int columnInteger = 0; columnInteger < 4; columnInteger ++) { nameString[rowInteger, columnInteger] = ""; //Initialize each element. }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Printing a Two-Dimensional Table Use a foreach loop to print one array element per line To print an entire row in one line, use a for loop and set the X and Y coordinates to print multiple elements per line // Print one name per line. foreach (string elementString in nameString) { // Set up a line. e.Graphics.DrawString(elementString, printFont, Brushes.Black, printXFloat, printYFloat); // Increment the Y position for the next line. printYFloat += lineHeightFloat; }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Summing a Two-Dimensional Table Include a total field for each row and each column Sum the figures in both directions (double check the totals) –Each column and row needs one total variable Two one- dimensional arrays work well for totals

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Lookup Operation for Two-Dimensional Tables - 1 Use same techniques as for single dimension arrays –Direct reference – If meaningful row and column subscripts are available –Table lookup Many 2D tables used for lookup will require additional one-dimensional arrays or lists to aid in the lookup process

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Lookup Operation for Two-Dimensional Tables - 2 Example - User selects the weight from one list and the zone from the second list –The SelectedIndex from the Weight list is used to find the correct row –The SelectedIndex from the Zone list is used to find the correct column