Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98.

Similar presentations


Presentation on theme: "1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98."— Presentation transcript:

1

2 1 Arrays and Strings Chapter 9

3 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting arrays Stepping through arrays Passing arrays as parameters

4 3 Design Problem l Consider a program to calculate class average Why?? ?

5 4 Add to Design Problem l Now your client says, I need to ALSO calculate and display “deviations” from the average Describe why this will or will NOT work

6 5 l Enter in the scores again l Use 100 separate variables » and cout and cin commands l Read (then re-read) from a file l The real answer … Possible Solutions  Use arrays !!  

7 6 Simple vs Structured Data Types l Simple data type => data element contains a single value l Structured data type => a data element contains a collection of data values x : 15 avg : ch : ‘A’ scores : name : ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’

8 7 Arrays l Arrays are Structured Data Types l They have a means of accessing individual components l Values can be retrieved from and stored in the structure scores : cout << scores[2]; scores[0] = 100;

9 8 One Dimensional Array l Structured collection of components » All of the same type l Structure given a single name l Individual elements accessed by index indicating relative position in collection l Type of elements stored in an array can be “just about” anything l Index of an array must be an integer

10 9 Use of Array for Our Problem l Store elements in array as read in l Go back and access for deviations Note declaration

11 10 Declaring Arrays l Syntax: Data_type Array_name [constant]; l Note declaration from our example Tells how many elements set aside

12 11 Declaring Arrays l Example specifies an array… » each element is an integer » there is space for 100 elements » the are numbered 0 through 99 scores :

13 12 Accessing Individual Components l Use the name of the array l Followed by an integer expression inside the square brackets [ ] scores : max = scores[0]; for (x = 0; x max) max = scores[x]; Index can be: - constant - variable - expression MUST be an integer

14 13 Out of Bounds Index l What happens if … l C++ does NOT check for index out of range l Possible to walk off into “far reaches” of memory -- clobbers... » other variable locations ».exe code » the operating system (??) float f_list [50]; f_list [100] = ; float f_list [50]; f_list [100] = ;

15 14 Initializing Arrays in Declarations l Possible to declare the size & initialize l Possible to omit size at declaration » Compiler figures out size of array int results [5] = {14, 6, 23, 8, 12 } float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }

16 15 Aggregate Operations l Defn => an operation on the data structure as a whole » as opposed to operation on a SINGLE element within the structure l Example » would be nice to read in a WHOLE array

17 16 Lack of Aggregate Operations l Would be nice but... C++ does NOT have... l Assignment operator for whole array l Arithmetic operations for whole array (think matrix) l Comparisons for arrays (not even = =) l Return of an array type by a function

18 17 How to Accomplish Aggregate Operations? l Most such tasks (assignment, read, write) can be performed some other way » CS II course will write “classes” to provide these functions l Otherwise » these operations must be performed by the programmer » element by element in a loop

19 18 Arrays as Parameters l This is one task that CAN be done to the WHOLE array l C++ always passes arrays by reference

20 19 Arrays as Parameters l The name of the array is a pointer constant l The address of the array is passed to the function l Size of the array also passed to control loop

21 20 Arrays as Parameters l Note the empty brackets in parameter list » A number can be placed here but it will be ignored

22 21 Sub-array Processing l Note we specified an array size of 100 » but we don’t anticipate that many scores l Array always declared larger than needed l Must keep track of how many have been used » this is our limit when doing other things to the array

23 22 C-Strings or Character Arrays l We have learned that the elements of an array can be just about anything l Consider an array whose elements are all characters » Called a C-String » Has a collection of special routines » Treated differently for I/O than other types of arrays

24 23 Declaration of C-Strings Similar to declaration of any array char name[30]; // no initialization char title [20] = "Le Grande Fromage"; // initialized at declaration // with a string char chList [10] = {'a', 'b', 'c', 'd'}; // initialized with list of char // values

25 24 Working with Character Strings l String => a collection of characters interpreted as a single item » a structured data item » in C++ a null-terminated sequence of characters stored in a char array l All strings in C++ are terminated by the null character » character 0, ‘\0’

26 25 Initializing Strings l When a character array is declared, it is legal to use the assignment operator to initialize l Note : use of the = operator only legal for char array initialization l But : aggregate array assignment is NOT greeting = “don’t do it;

27 26 String Output l Strings (character arrays) are handled differently than other types of arrays l This would NOT be allowed l This is legal: int num_list [100];... cout << num_list; char name [30] = “Snidly Q. Fizbane”;... cout << name;

28 27 String Input l Declare strings 1 element bigger than planned size to allow for ‘\0’ l When input takes place, C++ automatically places the ‘\0’ in memory at the end of the characters typed in

29 28 Problems with >> for String Input l Cannot be used to input a string with imbedded blanks l >> stops reading as soon as it encounters first whitespace character

30 29 Problems with >> for String Input Solve problem by using getline ( … ) Quits reading after 15 characters or when it hits a newline, whichever comes first. Includes all characters including spaces, tabs, etc (whitespace characters)

31 30 Problems with >> for String Input l If declared string is too small >> keeps putting characters in memory PAST that area in memory s2 contents extend into the memory area of s3

32 31 Using Strings Instead of “hard coding” file name for the open ( … ) command, » use a string variable, » use keyboard entry with cin.getline(…) » program more flexible, good for different files ifstream inFile; char fname[31]; cout “; cin.getline (fname, 30, ‘\n’); inFile.open (fname);

33 32 String Library Routines l Recall that we could not use the aggregate assignment of one string to another l C++ provides some string handling functions to do this (and other similar tasks) l Found in or

34 33 Contrast/Compare Strings and C-Strings Assignment is OK string s; s = "hi mom"; Comparison OK if (s < "geek") … I/O allowed cin >> s; cin.getline(s,'\n'); cout << s; Assignment is illegal char cs[30]; cs = "don't do it"; l Comparisons not allowed l I/O allowed much the same way

35 34 Working with C-Strings Functions provided in #include Used instead of assignment Used for comparisons

36 35 Another Problem l Some functions require C-strings as parameters » The.open() command for files The.open() command for files l C-strings are terminated by the null character (character 0) » Such functions are looking for that l String objects are built differently

37 36 Solving the File Open Problem l One of the functions available for a string object will convert it to a C-String The function is c_str() l Remember that string functions are called by using » The variable » The member operator var.c_str() » The name of the function l View example View example

38 37 Design Problem l Consider the task of keeping track of data about parts for manufacture » part number, description, qty needed, unit price

39 38 Design Problem l Use “Parallel” arrays l One array each for part num, descrip, qty, price l n th item in any one of the arrays associated with same n th item of all the arrays part #descripqtyprice A100xxx B25yyy

40 39 Testing and Debugging Hints l Range of legal index values is 0 to array_size - 1 l Individual elements of the array are of the component type l No aggregate operations in arrays » you must write the code to do this l If array parameter is incoming, specify formal parameter as const » prevents function from modifying

41 40 Testing and Debugging Hints l Omitting array size in declaration » when array declared formal parameter » when array initialized at declaration l Don’t pass component when function expects entire array l Declare array size as max ever needed » process only part of array which is used l Pass array name and length to functions which process array or sub array

42 41 Testing and Debugging l Be sure to account for null character when you manipulate characters individually in a string l Remember proper use of the = » correct for initialization at declarationtime » INCORRECT for aggregate assignment l Aggregate input/output allowed for strings but NOT for other array types

43 42 Testing and Debugging l If you use the >> for string input, make sure » string is declared large enough » string will have no white spaces l The >> operator stops at, but does not consume the first trailing white space » such as ‘\n’ or a space l The cin.getline (whatever, 30, ‘\n’ ) function » stops when reading the ‘\n’ » consumes the ‘\n’ » has problems when ‘\n’ is still in the input stream

44 43 Testing and Debugging When using the strcpy ( ), make sure that the destination array is declared long enough l Choose test data carefully for string handling programs » include strings that are too large » include strings with whitespace


Download ppt "1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98."

Similar presentations


Ads by Google