Download
c programming program design including data structures second edition n.
Skip this Video
Loading SlideShow in 5 Seconds..
C++ Programming: Program Design Including Data Structures, Second Edition PowerPoint Presentation
Download Presentation
C++ Programming: Program Design Including Data Structures, Second Edition

C++ Programming: Program Design Including Data Structures, Second Edition

228 Views Download Presentation
Download Presentation

C++ Programming: Program Design Including Data Structures, Second Edition

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. C++ Programming: Program Design Including Data Structures, Second Edition Chapter 9: Arrays and Strings

  2. Objectives In this chapter you will: • Learn about arrays • Explore how to declare and manipulate data into arrays • Understand the meaning of “array indexout of bounds” • Become familiar with the restrictions on array processing • Discover how to pass an array as a parameter to a function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  3. Objectives • Learn about C-strings • Examine the use of string functions to process C-strings • Discover how to input data in—and output data from—a C-string • Learn about parallel arrays • Discover how to manipulate data in a two-dimensional array • Learn about multidimensional arrays C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  4. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  5. Data Types • A data type is called simple if variables of that type can store only one value at a time • A structured data type is one in which each data item is a collection of other data items C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  6. Structured Data Type A structured data type is a type that • stores a collection of individual components withone variable name • and allows individual components to be stored and retrieved expanded by J. Goetz, 2004

  7. Declare variables to store and total 3 blood pressures int bp1, bp2, bp3; int total; 4000 4002 4004 bp1 bp2 bp3 cin >> bp1 >> bp2 >> bp3; total = bp1 + bp2 + bp3; expanded by J. Goetz, 2004

  8. 5000 5002 5004 5006 . . . . bp[0] bp[1] bp[2] . . . . bp[999] What if you wanted to store and total 1000 blood pressures? int bp[ 1000 ] ; // declares an array of 1000 int values expanded by J. Goetz, 2004

  9. Arrays • Array - a collection of a fixed number of components wherein all of the components have the same data type • One-dimensional array - an array in which the components are arranged in a list form • The general form of declaring a one-dimensional array is: dataType arrayName[intExp]; • where intExp is any expression that evaluates to a positive integer C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  10. 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. expanded by J. Goetz, 2004

  11. Another Example • Declare an array called temps which will hold up to 5 individual float values. float temps[5]; // declaration allocates memory number of elements in the array Base Address 7000 7004 7008 7012 7016 temps[0] temps[1] temps[2] temps[3] temps[4] indexes or subscripts expanded by J. Goetz, 2004

  12. Accessing Array Components • The general form (syntax) of accessing an array component is: arrayName[indexExp] where indexExp, called index, is any expression whose value is a nonnegative integer • The [] operator is called the array subscripting operator • Index value specifies the position of the component in the array • The array index always starts at 0 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  13. Assigning Values to Individual Array Elements float temps[ 5 ] ;// allocates memory for array int m = 4 ; temps[ 2 ] = 98.6 ; temps[ 3 ] = 101.2 ; temps[ 0 ] = 99.4 ; temps[ m ] = temps[ 3 ] / 2.0 ; temps[ 1 ] = temps[ 3 ] - 1.2 ; // what value is assigned? 7000 7004 7008 7012 7016 99.4 ? 98.6 101.2 50.6 temps[0] temps[1] temps[2] temps[3] temps[4] expanded by J. Goetz, 2004

  14. What values are assigned? float temps[ 5 ] ;// allocates memory for array int m ; for (m = 0; m < 5; m++) { temps[ m ] = 100.0 + m *0.2 ; } 7000 7004 7008 7012 7016 ? ? ? ? ? temps[0] temps[1] temps[2] temps[3] temps[4] expanded by J. Goetz, 2004

  15. Now what values are printed? float temps[ 5 ] ;// allocates memory for array int m ; . . . . . for (m = 4; m >= 0; m-- ) { cout << temps[ m ] << endl ; } 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 temps[0] temps[1] temps[2] temps[3] temps[4] expanded by J. Goetz, 2004

  16. Variable Subscripts float temps[ 5 ] ;// allocates memory for array int m = 3 ; . . . . . . What is temps[ m + 1] ? What is temps[ m ] + 1 ? 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 temps[0] temps[1] temps[2] temps[3] temps[4] expanded by J. Goetz, 2004

  17. 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 temps[0] temps[1] temps[2] temps[3] temps[4] A Closer Look at the Compiler float temps[5]; // this declaration allocates memory To the compiler, the value of the identifiertempsaloneis the base address of the array.We say temps is a pointer (because its value is an address).It “points” to a memory location. expanded by J. Goetz, 2004

  18. Processing One-Dimensional Arrays • Some basic operations performed on a one-dimensional array are: • Initialize • Input data • Output data stored in an array • Find the largest and/or smallest element • Each operation requires ability to step through the elements of the array • Easily accomplished by a loop C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  19. Accessing Array Components • Consider the declaration int list[100]; //list is an array of the size 100 int i; • This for loop steps-through each element of the array list starting at the first element for(i = 0; i < 100; i++) //Line 1 process list[i] //Line 2 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  20. inputting data into list • If processing list requires inputting data into list • the statement in Line 2 takes the from of an input statement, such as the cin statement for(i = 0; i < 100; i++) //Line 1 cin>>list[i]; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  21. Array Index Out of Bounds • If we have the statements: double num[10]; int i; • The component num[i] is a valid index if i = 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9 • The index of an array is in bounds if the index >=0 and the index <= arraySize-1 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  22. Array Index Out of Bounds • If either the index < 0 or the index > arraySize-1 • then we say that the index is out of bounds • There is no guard against indices that are out of bounds • C++ does not check if the index value is with in range • 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 declaredarray size minus one C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  23. Array Initialization • As with simple variables • Arrays can be initialized while they are being declared • When initializing arrays while declaring them • Not necessary to specify the size of the array • Size of array is determinedby the number of initial values in the braces • For example: double sales[] = {12.25, 32.50, 16.90, 23, 45.68}; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  24. Partial Initialization • The statement int list[10] = {0}; declares list to be an array of 10 components and initializes all components to zero • The statement int list[10] = {8, 5, 12}; declares list to be an array of 10 components, initializes list[0] to 8, list[1] to 5, list[2] to 12 and all other components are initialized to 0 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  25. Partial Initialization (continued) • The statement int list[] = {5,6,3}; declares list to be an array of 3 components and initializes list[0] to 5, list[1] to 6, and list[2] to 3 • The statement int list[25]= {4,7}; declares list to be an array of 25 components • The first two components are initialized to 4 and 7 respectively • All other components are initialized to zero C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  26. 6000 6002 6004 6006 6008 40 13 20 19 36 ages[0] ages[1] ages[2] ages[3] ages[4] Initializing in a Declaration int ages[ 5 ] = { 40, 13, 20, 19, 36 } ; for ( int m = 0; m < 5; m++ ) { cout << ages[ m ] ; } expanded by J. Goetz, 2004

  27. Restrictions on Array Processing • Assignment does not work with arrays • If x and y are two arrays of the same type and size then the following statement is illegal: y = x; // illegal • In order to copy one array into another array we must copy component-wise • This can be accomplished by a loop: for(j = 0; j < 25; j++) y[j] = x[j]; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  28. No Aggregate Array Operations • Comparison of arrays, reading data into an array and printing the contents of an array must be done component-wise cin>>x; //illegal cout<<y; //illegal • C++ does not allow aggregateoperations on an array • i.e. anyoperation that manipulates the entire array as a single unit C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  29. In C++, No Aggregate Array Operations • 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 • EXCEPTION: aggregate I/O is permitted for C-strings (special kinds of char arrays) – later in this chapter expanded by J. Goetz, 2004

  30. Arrays as Parameters to Functions • Arrays are passedby reference only • The symbol & is used when declaring an array as a formal parameter • whenever an array is passed as an argument, its base address is sent to the called function • The size of the array is usually omitted C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  31. Arrays as Parameters to Functions • If the size of one-dimensional array is specified when it is declared as a formal parameter • It is ignored by the compiler • The reserved word const in the declaration of the formal parameter can preventthe function from changingthe actual parameter C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  32. Using Arrays as Arguments to Functions Generally, functions that work with arrays require items of information as arguments: • the beginning memory address of the array (base address) • the number of elements to process in the array - might be less than the size of array • See next example expanded by J. Goetz, 2004

  33. Example with Array Parameters #include <iomanip> #include <iostream> void Obtain ( int [ ], int ) ; // prototypes here void FindWarmest ( const int[ ], int , int & ) ; void FindAverage ( const int[ ], int , int & ) ; void Print ( const int [ ], int ) ; using namespace std ; int main ( ) { int temp[31] ;// array to hold up to 31 temperatures int numDays ; int average ; int hottest ; int m ; 33 expanded by J. Goetz, 2004

  34. Example continued 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 ; } 34 expanded by J. Goetz, 2004

  35. Base Address 6000 50 65 70 62 68 . . . . . . temp[0] temp[1] temp[2] temp[3] temp[4] . . . . . temp[30] Memory Allocated for Array int temp[31] ; // array to hold up to 31 temperatures expanded by J. Goetz, 2004

  36. 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] ; } } 36 expanded by J. Goetz, 2004

  37. void Print ( /* in */const 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] ; } } 37 expanded by J. Goetz, 2004

  38. Use of const • because the identifier of an array holds the base address of the array, an & is never needed for an array in the parameter list • arrays are always passed by reference • to prevent elements of an array used as an argument from being unintentionally changed by the function, you place const in the function heading and prototype expanded by J. Goetz, 2004

  39. Use of const in prototypes void Obtain ( int [ ], int ) ; void FindWarmest ( const int [ ], int , int & ) ; void FindAverage ( const int [ ], int , int & ) ; void Print ( const int [ ], int ) ; do not use const with outgoing array because function is supposed to change array values use const with incoming array values to prevent unintentional changes by function expanded by J. Goetz, 2004

  40. void FindAverage ( /* in */const 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) ; } 40 expanded by J. Goetz, 2004

  41. void FindWarmest ( /* in */const 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] ; } } 41 expanded by J. Goetz, 2004

  42. Base Address of an Array • The base address of an array is the address, or memory location of the first array component • If list is a one-dimensional array • base address of list is the address of the component list[0] • When we pass an array as a parameter • base address of the actual array is passed to the formal parameter • Functions cannot return a value of the type array C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  43. //Arrays as parameters to functions #include <iostream> usingnamespace std; constint arraySize = 10; voidinitializeArray(int x[],int sizeX); voidfillArray(int x[],int sizeX); voidprintArray(constint x[],int sizeX); intsumArray(constint x[],int sizeX); intindexLargestElement(constint x[],int sizeX); voidcopyArray(constint x[], int y[], int length); int main() // Driver { int listA[arraySize] = {0}; //Line 1 int listB[arraySize]; //Line 2 cout << "Line 1: listA elements: "; //Line 3 printArray(listA, arraySize); //Line 4 cout << endl; //Line 5 initializeArray(listB, arraySize); //Line 6 cout << "Line 7: ListB elements: "; //Line 7 printArray(listB, arraySize); //Line 8 cout << endl << endl; //Line 9 cout << "Line 10: Enter " << arraySize << " integers: "; //Line 10 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  44. fillArray(listA, arraySize); //Line 11 cout << endl; //Line 12 cout << "Line 13: After filling listA elements are:" << endl; //Line 13 printArray(listA, arraySize); //Line 14 cout << endl << endl; //Line 15 cout << "Line 16: Sum of the elements of listA is: " << sumArray(listA, arraySize) << endl << endl; //Line 16 cout << "Line 17: Position of the largest element in listA is: " << indexLargestElement(listA, arraySize) << endl; //Line 17 cout << "Line 18: Largest element in listA is: " << listA[indexLargestElement(listA, arraySize)] << endl << endl; //Line 18 copyArray(listA, listB, arraySize); //Line 19 cout << "Line 20: After copying the elements of " << "listA into listB" << endl << " listB elements are: "; //Line 20 printArray(listB,arraySize); //Line 21 cout << endl; //Line 22 return 0; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  45. //Function to find and return the index of the //largest element of an array intindexLargestElement(constint list[], int listSize) { int counter; int maxIndex = 0; //Assume first element is the largest for (counter = 1; counter < listSize; counter++) if (list[maxIndex] < list[counter]) maxIndex = counter; return maxIndex; } //Function to copy one array into another array //The array listB must be at least as large as the array listA. voidcopyArray(constint listA[], int listB[], int listASize) { int counter; for (counter = 0; counter < listASize; counter++) listB[counter] = listA[counter]; } //Function to initialize an array to 0 voidinitializeArray(int list[], int listSize) { int counter; for (counter = 0; counter < listSize; counter++) list[counter] = 0; } //Function to read data and store in an array voidfillArray(int list[], int listSize) { int counter; for (counter = 0; counter < listSize; counter++) cin >> list[counter]; } //Function to print the array void printArray(constint list[], int listSize) { int counter; for (counter = 0; counter < listSize; counter++) cout << list[counter] << " "; } //Function to find and return the sum of an array intsumArray(constint list[], int listSize) { int counter; int sum = 0; for (counter = 0; counter < listSize; counter++) sum = sum + list[counter]; return sum; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  46. Array with enum Index Type DECLARATION enum Department { WOMENS, MENS, CHILDRENS, LINENS, HOUSEWARES, ELECTRONICS }; float salesAmt [ 6 ] ; Department which; USE for ( which = WOMENS ; which <= ELECTRONICS; which = Department ( which + 1 ) ) cout << salesAmt [ which ] << endl; 46 expanded by J. Goetz, 2004

  47. float salesAmt[6]; • The index has semantic content: • salesAmt [ WOMENS ] ( i. e. salesAmt [ 0 ] ) • salesAmt [ MENS] ( i. e. salesAmt [ 1 ] ) • salesAmt [ CHILDRENS ] ( i. e. salesAmt [ 2 ] ) • salesAmt [ LINENS ] ( i. e. salesAmt [ 3 ] ) • salesAmt [ HOUSEWARES ] ( i. e. salesAmt [ 4 ] ) • salesAmt [ ELECTRONICS ] ( i. e. salesAmt [ 5 ] ) expanded by J. Goetz, 2004

  48. C Strings (Character Arrays) • Character array - an array whose components are of type char • String - a sequence of >= 0 characters enclosed in double quote marks • C stings are null terminated (‘\0’) • The last character in a string is the null character • char ch =‘\0’ // stores the null chr C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  49. ASCII and EBCDIC • ASCII (pronounced ask-key) and EBCDIC are the two character sets commonly used to represent characters internally as integers • ASCII is used on most personal computers, and EBCDIC is used mainly on IBM mainframes • using ASCII the character ‘A’ is internally stored as integer 65. • Using EBCDIC the ‘A’ is stored as 193. • In both sets, the successive alphabet letters are stored as successive integers. • This enables character comparisons with ‘A’ less than ‘B’, etc. expanded by J. Goetz, 2004

  50. Right Digit Left Digit(s) 3 ” ! “ # $ % & ‘ 4 ( ) * + , - . / 0 1 5 2 3 4 5 6 7 8 9 : ; 6 < = > ? @ A B C D E 7 F G H I J K L M N O 8 P Q R S T U V W X Y 9 Z [ \ ] ^ _ ` a b c 10 d e f g h I j k l m 11 n o p q r s t u v w 12 x y z { | } ~ ASCII (Printable) Character Set0 1 2 3 4 5 6 7 8 9 50 expanded by J. Goetz, 2004