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.

Slides:



Advertisements
Similar presentations
Array. Convert Numbers in Different Base Systems Generate values to a series of numbers in different base systems: Base is between 2 and 9; Maximum number.
Advertisements

1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
1 Techniques of Programming CSCI 131 Lecture 24 Structs.
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
Informática II Prof. Dr. Gustavo Patiño MJ
Dale/Weems/Headington
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
 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
Arrays.
Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize & display Part I.
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
1 Lecture 22 Chapter 12 Arrays Dale/Weems/Headington.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Arrays One-Dimensional initialize & display Arrays as Arguments Part I.
1 Chapter 11 One-Dimensional Arrays. 2 Chapter 11 Topics l Atomic and composite data types l Declaring and instantiating an array l The length of an array.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Chapter 8 Arrays and Strings
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Data Structures (Terminology) Static Set at compile time Dynamic Set at run time.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Chapter 12-2 Arrays Dale/Weems. 2 Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information n.
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 12 Arrays. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Arrays. 2 Chapter 12 Topics  One-Dimensional Arrays  Using const in Function Prototypes  Using an Array of struct or class Objects  Using an enum.
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.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 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 Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
Fall 1999CS Composite Data Types. Fall 1999CS Topics to be Covered l Abstract data types l One-dimensional arrays l Two-dimensional arrays.
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.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
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.
Module 1: Array ITEI222 - Advance Programming Language.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Chapter 11 Arrays.
Dale/Weems/Headington
C++ Data Types Simple Structured Address Integral Floating
Pointers, Dynamic Data, and Reference Types
Chapter 11 Arrays.
Arrays Arrays A few types Structures of related data items
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

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 float double long double

3 Structured Data Type A structured data type is a type that l stores a collection of individual components with one variable name l and allows individual components to be stored and retrieved

4 Declare variables to store and total 3 blood pressures int bp1, bp2, bp3; int total; bp2bp1bp3 cin >> bp1 >> bp2 >> bp3; total = bp1 + bp2 + bp3;

5 What if you wanted to store and total 1000 blood pressures? int bp[ 1000 ] ; // declares an array of 1000 int values bp[0] bp[1] bp[2].... bp[999] C....

6 One-Dimensional Array Definition An array is a structured collection of components (called array elements), all of the same data type, given a single name, and stored in adjacent memory locations. The individual components are accessed by using the array name together with an integral valued index in square brackets. The index indicates the position of the component within the collection.

7 Another Example Declare an array called temps which will hold up to 5 individual float values. float temps[5]; // declaration allocates memory temps[0] temps[1] temps[2] temps[3] temps[4] C 7010 number of elements in the array Index of array (0-4) Base Address (in hexadecimal)

8 Declaration of an Array l in C++, the first array element always has index 0. The second array element has index 1, etc. l the base address of an array is its beginning address in memory SYNTAX DataType ArrayName [ConstIntExpression];

9 ConstIntExpression The array size must be a constant integer expression. Some examples: int scores[45]; const int MAXSTUDENTS = 100; string names[MAXSTUDENTS]; //good way float grades[45*6]; int size; cin >> size; int bp[size]; // WRONG Int bp[45.0]; // WRONG

10 Assigning Values to Individual Array Elements float temps[ 5 ] ; // allocates memory for array int m = 4 ; temps[ 2 ] = 98.6 ; temps[ 3 ] = ; temps[ 0 ] = 99.4 ; temps[ m ] = temps[ 3 ] / 2.0 ; temps[ 1 ] = temps[ 3 ] ; // what value is assigned? temps[0] temps[1] temps[2] temps[3] temps[4] C ?

11 Important Note l Arrays are indexed from 0 l So temps[5] DOES NOT EXIST! l COMMON SOURCE OF ERRORS!

12 What values are assigned? float temps[ 5 ] ; // allocates memory for array int m ; for (m = 0; m < 5; m++) // COMMON ERROR m<=5 { temps[ m ] = m  0.2 ; } temps[0] temps[1] temps[2] temps[3] temps[4] C 7010 ? ? ? ? ?

13 Now what values are printed? float temps[ 5 ] ; // allocates memory for array int m ;..... for (m = 4; m >= 0; m-- ) { cout << temps[ m ] << endl ; } temps[0] temps[1] temps[2] temps[3] temps[4]

14 Variable Subscripts float temps[ 5 ] ; // allocates memory for array int m = 3 ; What is temps[ m + 1] ? What is temps[ m ] + 1 ? temps[0] temps[1] temps[2] temps[3] temps[4] C

15 A Closer Look at the Compiler float temps[5]; // this declaration allocates memory To the compiler, the value of the identifier temps alone is the base address of the array. We say temps is a pointer (because its value is an address). It “points” to a memory location. temps[0] temps[1] temps[2] temps[3] temps[4] C

16 Initializing in a Declaration int ages[ 5 ] = { 40, 13, 20, 19, 36 } ; for ( int m = 0; m < 5; m++ ) { cout << ages[ m ] ; } ages[0] ages[1] ages[2] ages[3] ages[4] C

17 Passing Arrays as Arguments l in C++, arrays are always passed by reference l whenever an array is passed as an argument, its base address is sent to the called function

18 In C++, No Aggregate Array Operations l the only thing you can do with an entire array as a whole (aggregate) with any type of component elements is to pass it as an argument to a function int a[100]; int b[100]; cout << a; // WRONG a = b; // WRONG for ( i=0;i < 100;i++ ) //RIGHT a[i] = b[i];

19 Character array Declare an array called name which will hold up to 10 individual char values. char name[10]; // declaration allcates memory number of elements in the array name[0] name[1] name[2] name[3] name[4]..... name[9] Base Address

20 Character arrays (Cstrings) l Character arrays (Cstrings) were the original way to declare character strings l Replaced by strings l Sometimes needed for C++ functions (open was an example) l Convert string to Cstring via c_str() fileID.open(stringName.c_str());

21 Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information as arguments: l the beginning memory address of the array (base address). This is the array name l the number of elements to process in the array

22 #include void Obtain ( int [ ], int ) ; // prototypes here void FindWarmest ( int[ ], int, int & ) ; void FindAverage ( int[ ], int, int & ) ; void Print ( int [ ], int ) ; using namespace std ; int main ( ) { int temp[31] ; // array to hold up to 31 temperatures int numDays ; int average ; int hottest ; Example with Array Parameters 22

23 cout << “How many daily temperatures? ” ; cin >> numDays ; Obtain( temp, numDays ) ; // call passes value of numDays and // address of array temp to function cout << numDays << “ temperatures“ << endl ; Print ( temp, numDays ) ; FindAverage ( temp, numDays, average ) ; FindWarmest ( temp, numDays, hottest ) ; cout << endl << “Average was: “ << average << endl ; cout << “Highest was: “ << hottest << endl ; return 0 ; } Example continued 23

24 Memory Allocated for Array temp[0] temp[1] temp[2] temp[3] temp[4]..... temp[30] 6000 Base Address int temp[31] ; // array to hold up to 31 temperatures

25 void Obtain ( /* out */ int temp [ ], /* in */ int number ) // Has user enter number temperature values at keyboard // Precondition: // number is assigned && number > 0 // Postcondition: // temp [ 0.. number -1 ] are assigned { int m; for ( m = 0 ; m < number; m++ ) { cout << “Enter a temperature : “ ; cin >> temp [m] ; } 25

26 void Print ( /* in */ int temp [ ], /* in */ int number ) // Prints number temperature values to screen // Precondition: // number is assigned && number > 0 // temp [0.. number -1 ] are assigned // Postcondition: // temp [ 0.. number -1 ] have been printed 5 to a line { int m; cout << “You entered: “ ; for ( m = 0 ; m < number; m++ ) { if ( m % 5 == 0 ) cout << endl ; cout << setw(7) << temp [m] ; } 26

27 void FindAverage ( /* in */ int temp [ ], /* in */ int number, /* out */ int & avg ) // Determines average of temp[0.. number-1] // Precondition: // number is assigned && number > 0 // temp [0.. number -1 ] are assigned // Postcondition: // avg == arithmetic average of temp[0.. number-1] { int m; int total = 0; for ( m = 0 ; m < number; m++ ) { total = total + temp [m] ; } avg = int (float (total) / float (number) +.5) ; } 27

28 void FindWarmest ( /* in */ int temp [ ], /* in */ int number, /* out */ int & largest ) // Determines largest of temp[0.. number-1] // Precondition: // number is assigned && number > 0 // temp [0.. number -1 ] are assigned // Postcondition: // largest== largest value in temp[0.. number-1] { int m; largest = temp[0] ; // initialize largest to first element // then compare with other elements for ( m = 0 ; m < number; m++ ) { if ( temp [m] > largest ) largest = temp[m] ; } 28

29 More about Array Index l it is programmer’s responsibility to make sure that an array index does not go out of bounds. The index must be within the range 0 through the declared array size minus one l using an index value outside this range causes the program to access memory locations outside the array. The index value determines which memory location is used. THIS WILL CAUSE YOUR PROGRAM TO EXECUTE INCORRECTLY OR BE TERMINATED BY THE OPERATING SYSTEM.

30 Parallel Arrays DEFINITION Parallel arrays are 2 or more arrays that have the same index range, and whose elements contain related information, possibly of different data types. EXAMPLE const int SIZE 50 ; int idNumber [ SIZE ] ; float hourlyWage [ SIZE ] ; parallel arrays

31 const int SIZE 50 ; int idNumber [ SIZE ] ; // parallel arrays hold float hourlyWage [ SIZE ] ; // related information idNumber [ 0 ] 4562 hourlyWage [ 0 ] 9.68 idNumber [ 1 ] 1235 hourlyWage [ 1 ] idNumber [ 2 ] 6278 hourlyWage [ 2 ] idNumber [ 48 ] 8754 hourlyWage [ 48 ] idNumber [ 49 ] 2460 hourlyWage [ 49 ] 8.97

32 Two-Dimensional Array is a collection of components, all of the same type, structured in two dimensions, (referred to as rows and columns). Individual components are accessed by a pair of indexes representing the component’s position in each dimension. DataType ArrayName [ConstIntExpr] [ConstIntExpr]... ; SYNTAX FOR ARRAY DECLARATION

33 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] row 2, col 7 might be Arizona’s high for August EXAMPLE -- To keep monthly high temperatures for all 50 states in one array. const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; [ 0 ] [ 1 ] [ 2 ].. stateHighs [2] [7]. [ 48 ] [ 49 ]

34 Finding the average high temperature for Arizona int total = 0 ; int month = 0; int average ; while ( month < NUM_MONTHS ) // NOT <= { total = total + stateHighs [ 2 ] [ month ] ; month++; } average = int ( total / ) ; average 85

35 Multiple Dimensions l Arrays can have any number of dimensions l For example, state high temperatures by month and year l int stateHighs[state][month][year]

36 Using arrays for input data An array can be used to hold data read from a file: int studentID[100]; // max 100 students string lastName[100]; // last name char courseGrade[100]; // letter grade

37 // Read first line from file int index = 0; studentFile >> studentID[index] >> lastName[index] >> grade[index];

38 while (studentFile) // while not EOF { // Print the line cout << studentID[index]<<"\t" << lastName[index]<<"\t" << grade[index]<<endl; index++; // increment array index // read next line studentFile >> studentID[index] >> lastName[index] >> grade[index]; }