More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays.

Slides:



Advertisements
Similar presentations
Strings.
Advertisements

Chapter 10.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Chapter 8 Arrays and Strings
1 Arrays & functions Each element of an array acts just like an ordinary variable: Like any ordinary variable, you can pass a single array element to a.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 8 Arrays and Strings
Microsoft Visual C++.NET Chapter 61 Memory Management.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
(continue) © by Pearson Education, Inc. All Rights Reserved.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type.
Pointers & Dynamic Data Structures Chapter Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 Data Structures CSCI 132, Spring 2014 Lecture 10 Dynamic Memory and Pointers.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Lecture 25: Practical Training on Pointers. 2 Lecture Contents: t Reminder on Arrays t Reminder on Strings t Reminder on Pointers t Demo programs, Exercises.
1 Chapter 11 Structured Data. 2 Topics 10.1 Abstract Data Types 10.2 Combining Data into Structures 10.3 Accessing Structure Members 10.4 Initializing.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Defining a 2d Array A 2d array implements a MATRIX. Example: #define NUMROWS 5 #define NUMCOLS 10 int arr[NUMROWS][NUMCOLS];
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
CPS120: Introduction to Computer Science Lecture 15 Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Arrays.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Multi-dimensional Array 1 Multi-dimensional array refers to an array with more than one index. It is a logical representation. On physical storage, the.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
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.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Computer Programming BCT 1113
CSCE 210 Data Structures and Algorithms
7 Arrays.
Pointers, Dynamic Data, and Reference Types
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
7 Arrays.
Arrays Arrays A few types Structures of related data items
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Chapter 1 c++ structure C++ Input / Output
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Arrays and classes You can have arrays of objects –element class - use array of elements to store data needed for amino acid program –Money class - use an array of Money objects to store all the prices for a customer You can have arrays inside classes –a Molecule class could have an array of all the elements in the molecule –an Inventory class could have an array of all the items stocked by a store

Arrays vs classes Sometimes you can accomplish the same thing easier with classes –nX3 array of numbers to represent a series of cartesian points –1-D array of 3D_point objects Parallel arrays vs array of objects –arrays of objects easier to keep data todgether

4/15/02 Exam 3

Why multiple dimensions Sometimes it is useful to have arrays of more than one dimension. – a game program that used a checkerboard: represent the squares as elememts of a 2D array –array of words, you could use a 2-D array of char

Multi-D arrays Think of 2-D arrays as arrays of a particular kind of 1-D array. –The first index tells you how many of these 1-D arrays you are declaring, –the second index gives the the size these 1-D arrays. 3-D arrays are arrays of 2_D arrays, etc. –more than two or three dimensions not common.

Declaring 2-D arrays similar to one dimensional arrays. int matrix[8][6]; –declares an 8 by 6 array of ints, i.e. an array of 8 6-element arrays char wordList[10][20]; –declares an array of 10 cstrings, each of which can have 19 characters

Declaring 2 Dimensional Arrays Declaration charticTacToe [3][3]; Storage location ticTacToe [1][2] Name Row Column

Example const int Num_Rows = 11; const int Seats_In_Row = 9; string seatPlan [Num_Rows][Seats_In_Row];

Initialization const int Num_Rows = 2; const int Num_Cols = 3; float matrix[Num_Rows][Num_Cols] ={{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}}; Nested loops with two-dimensional arrays SumMatrx.cpp example

Bigger Arrays const int people = 10; const int years = 5; money sales[people][years][12];

Accessing elements access single elements with indices just the same way as you do those of 1-D arrays, matrix[2][3] wordList[1][5] access a single "row" with a single index matrix[2] wordList[1]

4/17/02

Dynamic Arrays Arrays we have looked at so far are static - size is fixed sometimes you don't know how many elements you will need To understand dynamic arrays, we need to understand pointers

Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the address of an int; memory is allocated for the address (pointer) but not the int

Pointing to an existing int int i = 25; Allocates memory for an int and stores the valkue 25 int * iptr; Allocates memory for a pointer to an int iptr = & i; sets the value of iptr to the address of i i and *iptr are the same –changing either one will change the other

Creating a new int int j = 15; Allocates momory for an int and stores the value 15 int * jptr; = new int; sets aside memory for an int and puts the address int j *j = j; stores value of j in memory pointed to by jptr

Pointers and Dynamic arrays A dynamic array is declared as a pointer int * iArray; use new to allocate appropriate amount of memory iArray = new int[ desiredSize]; use iArray just like you use any array iArray[index] = someValue;

Changing the size Allocate a new block of memory with new int *temp = new int[newSize]; Copy the elements in the current memory for (int j=0; j<currentSize; j++) temp[j] = iArray[i]; delete the old memory –delete [] iArray; reassign the pointer iarray = temp;

4/19 Design Exercise dynamic array class (section 1) command line arguments getline more on pointers

Command line arguments g++ -o prog prog.cpp Your programs can do this too

use a different prototype for main int main( int argc, char ** argv) {... } argc is the number of "words" in the command line (space delimited) including the name of the program argv is a 2-D array of char –uses pointer notation

reading text Think of a filestream as a sequence of characters When you open the stream, the file pointer is at the beginning

reading with >> cin >> word => word = now cin >> word => word = is

reading with getline getline( cin, line) => line = " the time " getline( cin, line) => line = "for all good men"

Using operator>> and getline Behavior is basically the same for C-style strings (char arrays) and string objects there are two overloaded versions of getline –void istream::getline( char[], int) –void getline(istream &, string)

string Class used to store character strings #include string text; text = "a literal string"; cin >> text;// gets one word of text getline( cin, text);// gets to next newline

reading C-style strings char a[10]; cin >> a; whitespace delimited to read multiple words, use getline cin.getline( a, 10); the number is the number of elements in the array

getline with delimiters You may sometimes have data separated by other characters than the newline –spreadsheet and database programs will usually print out tab or comma separated text two versions of getline allow you to specify the delimiter –void istream::getline( char[], int, char) –void getline(istream &, string, char)

char input reading into a char with >> skips whitespaces if you need to get the space characters –istream::get( ch)

Pointers and the “new” Operator Pointer Declarations –pointer variable of type “pointer to double” –can store the address of a double t in p double *p; The new operator creates a variable of type double & puts the address of the variable in pointer p p = new double; Dynamic allocation - memory is allocated while the program is running instead of before it starts

Pointers Actual address has no meaning Form:type*variable; Example: double *p; ? P

new Operator Actually allocates storage Form:new type; // one memory location new type [n]; // n memory locations Example:new double;

Pointer Variables If they aren't used for arrays, you have to use them differently

Accessing Data with Pointers * - indirection operator *p = 15.5; Stores floating value 15.5 in memory location *p - the location pointed to by p 15.5 p

Pointer Statements double*p; p = new doublet; *p = 15.5; cout << “The contents of the memory cell pointed to by p is “ << *p << endl; Output The contents of memory cell pointed to by p is 15.5

Pointer Operations Pointers can only contain addresses So the following are errors: p = 1000; p = 15.5; You need to assign an address to p p = &varOfAppropriateType

Pointer Operations Assignment of pointers if q & p are the same pointer type q = p; p and q both refer to the same memeory location - tha same variable relational operations == and != compare addresses not the values stored at those addresses

Pointers to Objects class electric { public: string current; int volts; }; electric*p,*q; p and q are pointers to objects of type electric

Pointers to Structs p = new electric; Allocates storage for struct of type electric and places address into pointer p ?? currentvoltsp

Assignments *p.current = “AC”; *p.volts = 115; Statements above can also be written –p ->current = “AC”; –p ->volts = 115; AC115 currentvoltsp

Struct Member Access via Pointers From:p ->m Example:p ->volts Example: –cout current volts << endl; Output –AC115

Pointers to Objects q = new electric; Allocates storage for object of type electric and places address into pointer q Copy contents of p struct to q struct *q = *p; AC115 q->currentq->voltsq

Pointers to Objects q->volts = 220; q = p; AC220 q->currentq->voltsq AC 115 AC220 q pq->currentq->volts p->currentp->volts

13.2 Manipulating the Heap When new executes where is struct stored ? Heap –C++ storage pool available to new operator Effect of p = new node; Figure 14.1 shows Heap before and after executing new operator

Effect on new on the Heap

Returning Cells to the Heap Operation –delete p; Returns cells back to heap for re-use When finished with a pointer delete it Watch dual assignments and initialization Form:deletevariable; Example:deletep;