43
Chapter 5 Chapter 5 Arrays and Arrays and Strings Strings C Programming C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Chapter 5 Arrays and Strings C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Embed Size (px)

Citation preview

Chapter 5Chapter 5Arrays and Arrays and

StringsStringsC ProgrammingC Programming

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

2

A A arrayarray is a collection of variables of the same data type is a collection of variables of the same data type that are referred to by a common name.that are referred to by a common name.

Arrays may have from one to several dimensions, but the Arrays may have from one to several dimensions, but the one-dimensional arrayone-dimensional array is the most common. is the most common.

Arrays are convenient for grouping related variables Arrays are convenient for grouping related variables together.together.

A A character arraycharacter array is very commonly used because it can is very commonly used because it can hold hold stringsstrings..

Remember that C/C++ does not define a built-in Remember that C/C++ does not define a built-in string string datadata type (C++ does implement a type (C++ does implement a string classstring class), but ), but implements them as implements them as nullnull terminated terminated arrays of arrays of characterscharacters..

What are Arrays?What are Arrays?

3

Review of Characters in Review of Characters in MemoryMemory

You can represent a single character in code by You can represent a single character in code by ''BB''. . Note the use of Note the use of single quotessingle quotes around the character. around the character.

You can represent a string in code by You can represent a string in code by "Hello World""Hello World". . Note the use of Note the use of double quotesdouble quotes around the around the character(s).character(s).

In memory each character is stored in a single byte.In memory each character is stored in a single byte.

In memory each character of a In memory each character of a stringstring is stored in a is stored in a single byte and it is terminated with a single byte and it is terminated with a NULLNULL character. character.

Example:Example:

\0dlroW olleH

B

Memory

Character

String

NULL Character

4

One-Dimensional ArraysOne-Dimensional ArraysA one-dimensional array is a list of related A one-dimensional array is a list of related variables. Its general format is:variables. Its general format is:

The The typetype declares the base type for the elements of declares the base type for the elements of the array and the array and sizesize defines the number of elements defines the number of elements in the array. For example, the following code in the array. For example, the following code defines an array containing defines an array containing 1010 integers. integers.

To To indexindex value must be used to access an individual value must be used to access an individual element of an array. An index describes the element of an array. An index describes the position (relative to zero) of an element in an array.position (relative to zero) of an element in an array.In C/C++ ALL arrays are zero

based!

type var-name[size];

int sample[10];

5

One-Dimensional Arrays One-Dimensional Arrays (continued)(continued)

Here is a sample program that defines, loads, and then Here is a sample program that defines, loads, and then displays the contents of an array.displays the contents of an array.#include <iostream>

using namespace std;

int main() {

int sample[10]; // this reserves 10 integer elements

int t;

for( t = 0; t < 10; ++t ) // load the array

sample[t] = t;

for( t = 0; t < 10; ++t ) // display the array

cout << sample[t] << ' ';

return 0;

}

All arrays occupy contiguous memory locations.

6

One-Dimensional Arrays One-Dimensional Arrays (continued)(continued)

This example creates an array of This example creates an array of 88 integers. Each integers. Each element is identified by its index number. The element is identified by its index number. The valid valid indexesindexes for this array are for this array are 00 – – 77..

To reference/access the To reference/access the 44thth element of this array you element of this array you must use the following:must use the following:

What does this do? What does this do?

110056714881238453Array x with 8 elemen

ts.

Index 0 Index 7

int x[8]; // defines an array of 8 integers

cout << x[3] << endl; // Why the 3?

x[5] = 3467;

x[0] x[7]x[6]x[5]x[4]x[3]x[2]x[1]

total bytes = number of bytes in type x number of elements

7

One-Dimensional Arrays One-Dimensional Arrays (continued)(continued)

To process the data stored in an array, you reference To process the data stored in an array, you reference each individual element by specifying the each individual element by specifying the array’s namearray’s name and the and the indexindex number of the element. number of the element.

This example declares an integer array and initializes it:This example declares an integer array and initializes it:

In memory the array would look like this.In memory the array would look like this.

Array X with 2

elements.

Index 0

13512

int X[2]; // defines an array of two integers

X[0] = 12; // sets first element to 12

X[1] = 135; // sets second element to 135

8

One-Dimensional Arrays One-Dimensional Arrays (continued)(continued)Here is a program that defines an array of Here is a program that defines an array of 1010 elements, assigns each elements, assigns each

element to a random value, and displays the minimum and maximum values.element to a random value, and displays the minimum and maximum values.

#include <iostream>

#include <cstdlib>

using namespace std;

int main() {

int i, min_value, max_value;

int list[10]; // define an array of 10 integers

for(i = 0; i < 10; i++) list[i] = rand();

min_value = list[0]; // find minimum value

for(i = 1; i < 10; i++)

if( min_value > list[i] ) min_value = list[i];

cout << "minimum value: " << min_value << endl';

max_value = list[0]; // find maximum value

for(i = 1; i < 10; i++)

if( max_value < list[i] ) max_value = list[i];

cout << "maximum value: " << max_value << endl;

return 0;

}

9

Lab 1Lab 1Code:Code:#include <iostream>

using namespace std;

void main() {

int Ary[4];

for (int x = 0; x < 4; x++) {

cout << "Enter a whole number: ";

cin >> Ary[x];

}

for (int y = 0; y < 4; y++)

cout << "Element " << y << " contains " <<

Ary[y] << endl;

}

10

ArraysArraysYou You CANNOTCANNOT assign one array to another array. The assign one array to another array. The following is illegal.following is illegal.

You must manually copy each element of an array to You must manually copy each element of an array to the other array as follows:the other array as follows:

for( int i = 0; i < 10; i++)

a[i] = b[i];

int a[10];

int b[10];

a = b; // error -- illegal

11

No Bounds CheckingNo Bounds CheckingC/C++ performs C/C++ performs NONO bounds checking on arrays. bounds checking on arrays. Nothing prevents you from overrunning the end of an Nothing prevents you from overrunning the end of an array. It is your responsibility to make sure this does array. It is your responsibility to make sure this does not happen.not happen.int y[8];

for( int i = 0; i < 10; i++)

a[i] = i;

0 1 2 3 4 5 6 7 8 9

This memory hasbeen overlaid.NOT GOOD

Memory allocated for the array

All bets are now off concerning the well being of the program’s

execution.

12

Sorting ArraysSorting ArraysSorting the data contained in arrays is a common Sorting the data contained in arrays is a common operation. There are several type of sorts you can use:operation. There are several type of sorts you can use:

QuicksortQuicksort Shaker sortShaker sort Shell sortShell sort Bubble sortBubble sort

Since sorting arrays is so common, a standard library Since sorting arrays is so common, a standard library function is provided which implements the function is provided which implements the QuicksortQuicksort. . It is one of the fastest general purpose sorting routines It is one of the fastest general purpose sorting routines available.available.

The text covers the The text covers the BubbleBubble sort, but we will learn to sort, but we will learn to use the use the qsort() qsort() library function. This function is library function. This function is designed to sort an array of any type data in either designed to sort an array of any type data in either ascending or descending sequence. ascending or descending sequence.

13

The qsort() FunctionThe qsort() FunctionFormat:Format:

The The qsort()qsort() function implements a function implements a quick-sort quick-sort algorithmalgorithm to sort an array of to sort an array of numnum elements, each of elements, each of widthwidth bytes. bytes.

The argument The argument basebase is a is a pointerpointer to the base of the array to the base of the array (usually the first element of the array) to be sorted.(usually the first element of the array) to be sorted.

comparecompare is the name of a function, which is the name of a function, which MUSTMUST be be provided by you, that controls the sequence of the provided by you, that controls the sequence of the elements (ascending or descending). It is called elements (ascending or descending). It is called automatically by the automatically by the qsort()qsort() function and function and NOTNOT by you. by you.

qsort()qsort() overwrites this array with the sorted elements. overwrites this array with the sorted elements.

void qsort( void *base, // Start of target array

size_t num, // number of elements to sort

size_t width, // size in bytes of each element

// compare function used by the qsort()

(int (*)(const void *, const void *)) compare

)

14

The qsort() Function The qsort() Function (continued)(continued)The argument The argument comparecompare is a pointer to a user-supplied is a pointer to a user-supplied routine that compares two array elements and returns a routine that compares two array elements and returns a value specifying their relationship. value specifying their relationship. qsort()qsort() calls the calls the comparecompare routine one or more times during the sort, routine one or more times during the sort, passing pointers to two array elements on each call:passing pointers to two array elements on each call:

The routine must compare the elements, then return The routine must compare the elements, then return one of the following values:one of the following values:

<0<0 if elem1 is less than elem2if elem1 is less than elem2 00 if elem1 is equal to elem2if elem1 is equal to elem2 >0>0 if elem1 is greater than elem2if elem1 is greater than elem2

The array is sorted in increasing order, as defined by The array is sorted in increasing order, as defined by the comparison function. To sort an array in decreasing the comparison function. To sort an array in decreasing order, reverse the sense of “order, reverse the sense of “greatergreater thanthan” and “” and “less less thanthan” in the comparison function.” in the comparison function.

compare( (void *) elem1, (void *) elem2 );

15

Example of Using the qsort() Example of Using the qsort() FunctionFunction#include <iostream>

#include <stdlib.h>

using namespace std;

int Numeric(int *p1, int *p2) {

if (*p1 < *p2 ) return -1;

if (*p1 == *p2 ) return 0;

return 1;

}

int main() {

int A[5] = {345, 90000, 1, 56, 4000};

int i;

for(i = 0; i < 5; i++) // Display array before sorting

cout << setw(8) << A[i];

cout << endl;

qsort(&A, 5, sizeof(A[0]),(int(*) (const void *, const void *)) Numeric);

for(i = 0; i < 5; i++) // Display sorted array

cout << setw(8) << A[i];

cout << endl;

return 0;

}

16

The qsort() Function The qsort() Function (continued)(continued)OUTPUT:

345 90000 1 56 4000

1 56 345 4000 90000

The sizeof() function returns the number of bytes of memory allocatedfor the variable. int x;

int y[10];

int size;

char lastName[17];

cout << sizeof( x ); // displays 4

cout << sizeof( y ); // displays 40

size = sizeof( y[2] ); // sets size to 4

cout << sizeof( lastName ); // displays 17

cout << sizeof( int ); // displays 4

cout << sizeof( double ); // displays 8

17

StringsStringsC/C++ does not have a string data type. In C/C++, a C/C++ does not have a string data type. In C/C++, a string is defined as a character array terminated by a string is defined as a character array terminated by a null null ((‘\0’‘\0’). Because of this ). Because of this nullnull terminator, you will need to terminator, you will need to take this into consideration when calculating the number take this into consideration when calculating the number of characters it will take to store the string.of characters it will take to store the string.Examples:Examples:

The last name field can contain a maximum of The last name field can contain a maximum of 1515 characters.characters. You can You can NOTNOT do a direct assignment of strings like: do a direct assignment of strings like:

You can initialize a string variable at the declaration:You can initialize a string variable at the declaration: S a m S m i t h \0 ? ? ? ? ? ?

Always add 1 to the total number of Always add 1 to the total number of characters to account for the NULL characters to account for the NULL

terminator.terminator.

char Lname[16];

Lname = "Sam Smith"; // this is illegal

char Lname[16] = "Sam Smith";

18

Strings Strings (continued)(continued)

What does this create?What does this create?

This creates an empty string or This creates an empty string or null stringnull string..

Since strings are implemented as a one-dimensional Since strings are implemented as a one-dimensional array of array of charchar’s, we can access any individual ’s, we can access any individual character in the string by using an index value. character in the string by using an index value.

\o ? ? ? ? ? ? ?

char str[] = “ABCDEFGHI”;

cout << str[3]; // displays D

char Str[8] = “”;

19

Reading a String from the Reading a String from the KeyboardKeyboardThe easiest way is to define a string variable and use the The easiest way is to define a string variable and use the cincin

statement to input data from the keyboard into it.statement to input data from the keyboard into it.

#include <iostream>

using namespace std;

int main() {

char str[80];

cout << "Enter a string: ";

cin >> str; // read string from keyboard

cout << "Here is your string: ";

cout << str;

return 0;

}

Sample run:

Enter a string: This is a test

Here is your string: This

20

Reading a String from the Reading a String from the KeyboardKeyboardDo you see the problem? Only the word Do you see the problem? Only the word ThisThis is is

inputted by the inputted by the cincin statement. The reason for this is statement. The reason for this is that the that the cincin statement statement STOPSSTOPS inputting characters inputting characters from the keyboard buffer when a from the keyboard buffer when a whitespacewhitespace character is encountered.character is encountered.

WhitespaceWhitespace characters are: characters are:

spacesspaces tabstabs newlinesnewlines

One solution to this problem is to use the One solution to this problem is to use the gets()gets() library function. Its format is:library function. Its format is:gets(array-name);

21

Reading a String from the Reading a String from the KeyboardKeyboardHere is the same program from above, but it uses the Here is the same program from above, but it uses the

gets()gets() function instead of the function instead of the cincin statement. statement.#include <iostream>

#include <cstdio>

using namespace std;

int main() {

char str[80];

cout << "Enter a string: ";

gets(str); // read a string from the keyboard

cout << "Here is your string: ";

cout << str;

return 0;

}

Sample run:

Enter a string: This is a test

Here is your string: This is a test

22

Reading a String from the Reading a String from the KeyboardKeyboardFor reasons we will cover later, the name of a For reasons we will cover later, the name of a

character array that holds a string can be used any character array that holds a string can be used any place that a string literal can be used.place that a string literal can be used.

Remember: Neither the cin or the gets() performs any boundary checking on the array.

23

String Library FunctionsString Library FunctionsThe The cstringcstring library holds the functions for string library holds the functions for string

manipulation.manipulation.

Some of the more common string library functions Some of the more common string library functions are:are:

strcpy( dest, source ); strncpy( dest, source, number ); strcat( dest, source ); strncat( dest, source, number ); strcmp( str1, str2 ); strncmp( str1, str2, number ); strlen( source );

24

The strcpy() FunctionThe strcpy() FunctionFormat:Format:

This function makes a copy of This function makes a copy of sourcesource string and string and places it into the places it into the dest dest string.string.

strcpy(dest, source);

#include <iostream>

#include <cstring>

using namespace std;

int main() {

char str[80];

strcpy(str, "hello");

cout << str;

return 0;

}

OUTPUT:

hello

25

The strncpy() FunctionThe strncpy() FunctionFormat:Format:

This function makes a copy of a specific number of This function makes a copy of a specific number of characters in characters in sourcesource string and places it into the string and places it into the dest dest string.string.

strncpy(dest, source, number);

#include <iostream>

#include <cstring>

using namespace std;

int main() {

char s1[20];

char s2[] = "ABCDEFGHIJKLM";

strncpy(s1, s2, 6);

cout << s1;

return 0;

}

OUTPUT:

ABCDEF

26

The strcat() FunctionThe strcat() FunctionFormat:Format:

This function appends the This function appends the sourcesource string to the end string to the end of the of the dest dest string. This is called string. This is called concatenationconcatenation..

strcat(dest, source);

#include <iostream>

#include <cstring>

using namespace std;

int main() {

char s1[20], s2[10];

strcpy(s1, "hello");

strcpy(s2, " there");

strcat(s1, s2);

cout << s1;

return 0;

}

OUTPUT:

hello there

27

The strncat() FunctionThe strncat() FunctionFormat:Format:

This function appends a specific number of This function appends a specific number of characters in characters in sourcesource string to the end of the string to the end of the destdest string.string.

strncat( dest, source, number );

#include <iostream>

#include <cstring>

using namespace std;

int main() {

char s1[20] = "ABCDEF"

char s2[10] = "WXYZ";

strncat( s1, s2, 2 );

cout << s1;

return 0;

}

OUTPUT:

ABCDEFWX

28

The strcmp() FunctionThe strcmp() FunctionFormat:Format:

This function compares two strings. This function compares two strings.

It returns the following:It returns the following: aa negative value negative value if if str1str1 << str2str2 aa zero zero if the strings are if the strings are equalequal aa positive value positive value if if str1 str1 >> str2 str2..

strcmp( str1, str2 );

29

#include <iostream>

#include <cstring>

#include <cstdio>

using namespace std;

bool password();

int main() {

if( password() )

cout << "Logged on.\n";

else

cout << "Access denied.\n";

return 0;

}

bool password() { // Return true if password accepted; false otherwise.

char s[80];

cout << "Enter password: ";

gets(s);

if( strcmp( s, "password" ) ) { // strings differ

cout << "Invalid password.\n";

return false;

}

return true;

}

30

The strncmp() FunctionThe strncmp() FunctionFormat:Format:

This function compares a specified number of This function compares a specified number of characters in characters in str1str1 to the same number of characters to the same number of characters in in str2str2. It returns the same values as . It returns the same values as strcmp()strcmp()..

strncmp( str1, str2, number );

#include <iostream>

#include <cstring>

using namespace std;

int main() {

char str1[] = "ABCJKL";

if( strncmp( str, "ABC", 3 ) )

cout << "Found a match.\n";

else

cout << "Match not found.\n";

return 0;

}

OUTPUT:

Found a match

31

The strlen() FunctionThe strlen() FunctionFormat:Format:

This function returns the number of characters a This function returns the number of characters a string currently contains string currently contains excludingexcluding the the NULL NULL character.character.

strlen(source);

#include <iostream>

#include <cstdio>

#include <cstring>

using namespace std;

int main() {

char str[80];

cout << "Enter a string: ";

gets(str);

cout << "Length is: " << strlen(str) << endl;;

return 0;

}

SAMPLE EXECUTION:Enter a string: Hello worldLength is: 11

32

The strlen() Function The strlen() Function (continued)(continued)

The The strlen()strlen() function is a very useful function for processing the function is a very useful function for processing the individual characters of a string variable. Here is an example:individual characters of a string variable. Here is an example:

#include <iostream>

#include <cstdio>

#include <cstring>

using namespace std;

int main() { // Print a string backwards.

char str[80];

int i;

cout << "Enter a string: ";

gets(str);

for( i = strlen(str) - 1; i >= 0; i-- )

cout << str[i];

return 0;

}

33

Another strlen() Function Another strlen() Function ExampleExample#include <iostream>

#include <cstdio>

#include <cstring>

using namespace std;

int main() { // Scan a string to see if it contains only digits.

char str[80];

int i;

bool good = true;

cout << "Enter a string: ";

gets(str);

for( i = 0; i < strlen(str); i++ )

if( str[i] < ‘0’ || str[i] > ‘9’ ) {

good = false;

break;

}

if( good )

cout << “String contains only numbers” << endl;

else

cout << “Illegal character found: ” << str[i] << endl;

return 0;

}

34

Another strlen() Function Another strlen() Function ExampleExample

#include <iostream>

#include <cstdio>

#include <cstring>

using namespace std;

int main() { // Test for an overflow condition.

char str[80];

cout << "Enter a string: ";

gets(str);

if( strlen( str ) > 79 ) {

cout << “Overflow condition has occurred” << endl;

// this statement terminates the program

exit( EXIT_FAILURE ); }

return 0;

}

35

Sample CodeSample Code#include <iostream>

#include <cstring>

using namespace std;

char Source1[6] = "Hello";

char Source2[12] = "Hello Tommy";

char Dest[15] = "\0";

int main() {

cout << "The contents of Dest is " << Dest << ".\n\n";

cout << "Use strcpy to copy Source1 to Dest\n";

strcpy( Dest, Source1);

cout << "The contents of Dest is " << Dest << ".\n\n";

cout << "Use strncpy to copy Source2 to Dest\n";

strncpy( Dest, Source2, 9); cout << "The contents of Dest is " << Dest << ".\n\n";

cout << "Use strcat to append ' again' to Dest\n";

strcat( Dest, " again ");

cout << "The contents of Dest is " << Dest << ".\n\n";

36

cout << "Use strncat to append Source2 to Dest\n";

strncat( Dest, Source2, 9);

cout << "The contents of Dest is " << Dest << ".\n\n";

cout << "Use strcmp to compare Source1 to Source2\n"; if (strcmp( Source1, Source2) == 0)

cout << "The two strings are equal.\n\n";

else if (strcmp( Source1, Source2) < 0)

cout << "Source1 should pre ceed Source2.\n\n";

else if (strcmp( Source1, Source2) > 0)

cout << "Source2 should preceed Source1.\n\n";

cout << "Use strncmp to compare Source1 to Source2\n";

if (strncmp( Source1, Source2, 5) == 0)

cout << "The two strings are equal.\n\n";

else if (strncmp( Source1, Source2, 5) < 0)

cout << "Source1 should preceed Source2.\n\n";

else if (strncmp( Source1, Source2, 5) > 0)

cout << "Source2 should preceed Source1.\n\n";

}

37

OUTPUT:The contents of Dest is .

Use strcpy to copy Source1 to Dest

The contents of Dest is Hello.

Use strncpy to copy Source2 to Dest

The contents of Dest is Hello Tom.

Use strcat to append ' again' to Dest

The contents of Dest is Hello Tom again .

Use strncat to append Source2 to Dest

The contents of Dest is Hello Tom again Hello Tom.

Use strcmp to compare Source1 to Source2

Source1 should preceed Source2.

Use strncmp to compare Source1 to Source2

The two strings are equal.

Press any key to continue

38

Arrays Of StringsArrays Of StringsYou can create a two dimensional array of strings.You can create a two dimensional array of strings.#include <iostream>

#include <cstring>

using namespace std;

int main() { // The first number is how many rows the array has and the // second number is how many characters each record contains.

char Days[7][10] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday“ };

for( int loop = 0; loop < 7; loop++ ) cout << Days[loop] << "\n";

return 0;

}

39

Arrays Of Strings Arrays Of Strings (continued)(continued)

OUTPUT:

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Sunday

Press any key to continue

40

Arrays Of Strings Arrays Of Strings (continued)(continued)

M O N D A Y \0

T U E S D A Y \0

W E D N E S D A Y \0

T H U R S D A Y \0

F R I D A Y \0

S A T U R D A Y \0

S U N D A Y \0

[0][0]

[0][0] [0][1] [0][2] [0][3] [0][4] [0][5] [0][6] [0][7] [0][8] [0][9]

[1][0]

[2][0]

[3][0]

[4][0]

[5][0]

[6][0]

char Days[7][10] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday“ };

char Days[7][] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday“ };

These are equivalent:

41

ArraysArraysYou can initialize an array when it is declared.You can initialize an array when it is declared.

ExampleExample::

You can also create an array and initialize it without You can also create an array and initialize it without giving the number of elements it will be.giving the number of elements it will be.

ExampleExample::

int X[4] = {2, 5, 23, 177};

int X[] = {2, 5, 23, 177};

42

Sample ArraySample Array#include <iostream>

using namespace std;

void main() {

char monthNames[12][] = { “January”, “February“, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November” , “December” };

int month;

cout << “Enter month number ( 1 – 12 ): “;

cin >> month;

cout << “The month is: “ << monthNames[month] << endl;

return 0;

}

SAMPLE EXECUTION:

Enter month number ( 1 – 12 ): 10

The month is: November

What is the problem?

43

Corrected Sample ArrayCorrected Sample Array#include <iostream>

using namespace std;

void main() {

char monthNames[12][] = { “January”, “February“, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November” , “December” };

int month;

cout << “Enter month number ( 1 – 12 ): “;

cin >> month;

cout << “The month is: “ << monthNames[month - 1] << endl;

return 0;

}

SAMPLE EXECUTION:

Enter month number ( 1 – 12 ): 10

The month is: October