+ All Categories
Home > Documents > 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting...

1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting...

Date post: 18-Jan-2016
Category:
Upload: ethel-mclaughlin
View: 216 times
Download: 1 times
Share this document with a friend
43
1 Arrays and Strings
Transcript
Page 1: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

1

Arrays and Strings

Page 2: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

2

Declaring arrays

scores : 85 79 92 57 68 80 . . . scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

Inspecting arrays

Passing arrays as parameters

Page 3: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

3

Design Problem

Consider a program to calculate class average

Why??Why??

?

Page 4: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

4

Add to Design Problem

Now your client says, I need to ALSO calculate and display “deviations” from the average

Describe why this will or will NOT workDescribe why this will or will NOT work

Page 5: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

5

Enter in the scores again Use 100 separate variables

» and cout and cin commands Read (then re-read) from a file The real answer …

Possible Solutions

Use arrays!!

Page 6: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

6Simple vs Structured Data Types

Simple data type => data element contains a single value

Structured data type => a data element contains a collection of data values

x : 15x : 15 avg : 84.35avg : 84.35 ch : ‘A’ch : ‘A’

scores : 85 79 92 57 68 80scores : 85 79 92 57 68 80

name : ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’name : ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’

Page 7: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

7

Arrays

Arrays are Structured Data Types They have a means of accessing

individual components Values can be retrieved from and stored

in the structure

scores : 85 79 92 57 68 80scores : 85 79 92 57 68 800 1 2 3 4 5

cout << scores[2];scores[0] = 100;cout << scores[2];scores[0] = 100;

Page 8: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

8

One Dimensional Array

Structured collection of components» All of the same type

Structure given a single name Individual elements accessed by index

indicating relative position in collection Type of elements stored in an array can be

“just about” anything Index of an array must be an integer

Page 9: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

9Use of Array for Our Problem

Store elements in array as read in Go back and access for deviations

Note declarationNote declaration

Page 10: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

10

Declaring Arrays

Syntax: Data_type Array_name [constant];

Note declaration from our example

Tells how many elements set asideTells how many elements set aside

Page 11: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

11

Declaring Arrays

Example specifies an array…» each element is an integer» there is space for 100 elements» the are numbered 0 through 99

scores : 85 79 92 57 68 80 . . . scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

Page 12: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

12Accessing Individual Components

Use the name of the array Followed by an integer expression

inside the square brackets [ ]

scores : 85 79 92 57 68 80 . . . scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

max = scores[0];for (x = 0; x < 100; x++) if (scores[x] > max) max = scores[x];

max = scores[0];for (x = 0; x < 100; x++) if (scores[x] > max) max = scores[x];

Index can be:- constant- variable- expressionMUST be an integer

Index can be:- constant- variable- expressionMUST be an integer

Page 13: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

13

Out of Bounds Index What happens if …

C++ does NOT check for index out of range 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] = 123.456;

float f_list [50];

f_list [100] = 123.456;

Page 14: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

14Initializing Arrays in Declarations

Possible to declare the size & initialize

Possible to omit size at declaration» Compiler figures out size of array

int results [5] = {14, 6, 23, 8, 12 }int results [5] = {14, 6, 23, 8, 12 }

float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }

Page 15: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

15

Aggregate Operations

Defn => an operation on the data structure as a whole» as opposed to operation on a SINGLE

element within the structure Example

» would be nice to read in a WHOLE array

Page 16: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

16Lack of Aggregate Operations

Would be nice but . . . C++ does NOT have . . .

Assignment operator for whole array Arithmetic operations for whole array

(think matrix) Comparisons for arrays (not even = =) Return of an array type by a function

Page 17: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

17How to Accomplish Aggregate Operations?

Most such tasks (assignment, read, write) can be performed some other way» CS II course will write “classes” to

provide these functions Otherwise

» these operations must be performed by the programmer

» element by element in a loop

Page 18: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

18

Arrays as Parameters

This is one task that CAN be done to the WHOLE array

C++ always passes arrays by reference

Page 19: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

19

Arrays as Parameters

The name of the array is a pointer constant

The address of the array is passed to the function

Size of thearray alsopassed tocontrol loop

Page 20: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

20

Arrays as Parameters

Note the empty brackets in parameter list » A number can be placed here but it

will beignored

Page 21: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

21

Sub-array Processing

Note we specified an array size of 100» but we don’t anticipate that many scores

Array always declared larger than needed Must keep track of how many have been

used» this is our limit when doing other things to

the array

Page 22: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

22C-Strings or Character Arrays

We have learned that the elements of an array can be just about anything

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

Page 23: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

23

Declaration of C-Strings

Similar to declaration of any arraychar name[30];

// no initializationchar title [20] = "Le Grande Fromage"; // initialized at declaration

// with a stringchar chList [10] = {'a', 'b', 'c', 'd'}; // initialized with list of char

// values

Page 24: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

24Working with Character Strings

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 All strings in C++ are terminated by the null character

» character 0,‘\0’

Page 25: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

25

Initializing Strings

When a character array is declared, it is legal to use the assignment operator to initialize

Note : use of the = operator only legal for char array initialization

But : aggregate array assignment is NOT

greeting = “don’t do it;

Page 26: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

26

String Output

Strings (character arrays) are handled differently than other types of arrays

This would NOT be allowed

This is legal:

int num_list [100];. . .cout << num_list;

int num_list [100];. . .cout << num_list;

char name [30] = “Snidly Q. Fizbane”; . . .

cout << name;

char name [30] = “Snidly Q. Fizbane”; . . .

cout << name;

Page 27: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

27

String Input

Declare strings 1 element bigger than planned size to allow for ‘\0’

When input takes place, C++ automatically places the ‘\0’ in memory at the end of the characters typed in

Page 28: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

28Problems with >> for String Input

Cannot be used to input a string with imbedded blanks

>> stops reading as soon as it encounters first whitespace character

Page 29: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

29Problems with >> for String Input

Solve problem by using getline ( … )

Quits reading after 15 charactersor when it hits a newline,

whichever comes first.

Quits reading after 15 charactersor when it hits a newline,

whichever comes first.

Includes all charactersincluding spaces, tabs, etc

(whitespace characters)

Includes all charactersincluding spaces, tabs, etc

(whitespace characters)

Page 30: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

30Problems with >> for String Input

If declared string is too small >> keeps putting characters in memory PAST that area in memory

s2 contents extendinto the memory

area of s3

s2 contents extendinto the memory

area of s3

Page 31: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

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 filesifstream inFile;char fname[31];cout << “Enter file name -> “;cin.getline (fname, 30, ‘\n’);inFile.open (fname);

ifstream inFile;char fname[31];cout << “Enter file name -> “;cin.getline (fname, 30, ‘\n’);inFile.open (fname);

Page 32: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

32

String Library Routines Recall that we could not use the aggregate

assignment of one string to another C++ provides some string handling functions to

do this (and other similar tasks) Found in

<string.h>or <cstring>

Page 33: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

33

Contrast/Compare Strings and C-Strings

Assignment is OKstring s;s = "hi mom";

Comparison OKif (s < "geek") …

I/O allowedcin >> s;cin.getline(s,'\n');cout << s;

Assignment is illegalchar cs[30];cs = "don't do it";

Comparisons not allowed I/O allowed much the

same way

Page 34: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

34

Working with C-Strings

Functions provided in #include <cstring>

Used instead of assignment

Used for comparisons

Page 35: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

35

Another Problem

Some functions require C-strings as parameters» The .open() command for files

C-strings are terminated by the null character (character 0)» Such functions are looking for that

String objects are built differently

Page 36: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

36Solving the File Open Problem

One of the functions available for a string object will convert it to a C-String

The function is c_str() Remember that string functions are called by

using» The variable» The member operator var.c_str()» The name of the function

View example

Page 37: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

37

Design Problem

Consider the task of keeping track of data about parts for manufacture» part number,

description, qty needed, unit price

Page 38: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

38

Design Problem

Use “Parallel” arrays One array each for

part num, descrip, qty, price

nth item in any one of the arrays associated with same nth item of all the arrays

part # descrip qty price

A100 xxx 5 1.23

B25 yyy 23 8.95

0

1

2

Page 39: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

39Testing and Debugging Hints

Range of legal index values is 0 to array_size - 1 Individual elements of the array are of the

component type No aggregate operations in arrays

» you must write the code to do this If array parameter is incoming, specify formal

parameter as const » prevents function from modifying

Page 40: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

40Testing and Debugging Hints

Omitting array size in declaration» when array declared formal parameter» when array initialized at declaration

Don’t pass component when function expects entire array

Declare array size as max ever needed» process only part of array which is used

Pass array name and length to functions which process array or sub array

Page 41: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

41

Testing and Debugging

Be sure to account for null character when you manipulate characters individually in a string

Remember proper use of the = » correct for initialization at declarationtime» INCORRECT for aggregate assignment

Aggregate input/output allowed for strings but NOT for other array types

Page 42: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

42

Testing and Debugging If you use the >> for string input, make sure

» string is declared large enough» string will have no white spaces

The >> operator stops at, but does not consume the first trailing white space» such as ‘\n’ or a space

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

Page 43: 1 Arrays and Strings 2 Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98 99 Inspecting arrays Stepping through arrays Passing arrays as parameters.

43

Testing and Debugging

When using the strcpy ( ), make sure that the destination array is declared long enough

Choose test data carefully for string handling programs» include strings that are too large» include strings with whitespace


Recommended