Chapter 10 Arrays and Strings

10.1 Arrays 10.2 One-Dimensional Arrays
10.2.1 10.2.2 10.2.3 10.2.4 10.2.5 Accessing Array Elements Representation of Arrays in Memory Example: Finding the Maximum No Array-to-Array Assignments No Bounds Checking

10.3 Strings
10.3.1 Reading a String from the Keyboard 10.3.2 Some C++ Library Functions for Strings 10.3.3 Using the Null Terminator
Chapter Overview

10.4 Two-Dimensional Arrays 10.5 Multidimensional Arrays 10.6 Array Initialization
10.6.1 Character Array Initialization 10.6.2 Multi-Dimensional Array Initialization 10.6.3 Unsized Array Initializations

10.7 Arrays of Strings 10.8 An Example Using String Arrays
10.8.1 10.8.2 10.8.3 10.8.4 10.8.5 Entering Information Displaying Database Contents Menu For User´s Selection Main Function Putting It All Together

10.9 References

Chapter Overview

Page 3

Chapter 10: Arrays and Strings

10.1 Arrays
An array is a collection of variables of the same type that are referred to by a common name. Arrays offer a convenient means of grouping together several related variables, in one dimension or more dimensions: • product part numbers: int part_numbers[] = {123, 326, 178, 1209}; • student scores: int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4}; • characters: char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};

First

Back

TOC

Prev Next

Last

Page 4

Chapter 10: Arrays and Strings

• names: char names[][40] = {“Peter”, “Mary”, “Lisa”, “John”, "George-Simon"}; • 3D coordinates: vector {{0, {1, {1, {4, coordinates[4][3] = 0, 0}, 0, 1}, 0, 5} 7, 9}};

First

Back

TOC

Prev Next

Last

The general form of a one-dimensional array declaration is: type variable_name[size] • type: base type of the array. determines the data type of each element in the array how many elements the array will hold the name of the array • size: • variable_name: Examples: int sample[10]. ﬂoat float_numbers[100].Page 5 Chapter 10: Arrays and Strings © Christian Jacob 10. First Back TOC One-Dimensional Arrays Prev Next Last .2 One-Dimensional Arrays A one-dimensional array is a list of related variables. char last_name[40].

An index describes the position of an element within an array.Page 6 Chapter 10: Arrays and Strings © Christian Jacob 10.2.1 Accessing Array Elements An individual element within an array is accessed by use of an index. Note: In C++ the ﬁrst element has the index zero! First Back TOC One-Dimensional Arrays Prev Next Last .

t<10. // display the array for(t=0. // initialize the array for(t=0. ++t) sample[t] = t*t. return(0). // reserves for 10 integers int t. t<10.Page 7 Chapter 10: Arrays and Strings © Christian Jacob Example: Load the array sample with the numbers 02 through 92 #include <iostream. ++t) cout << sample[t] << ‘ ‘.} First Back TOC One-Dimensional Arrays Prev Next Last .h> int main() { int sample[10].

Page 8 Chapter 10: Arrays and Strings © Christian Jacob 10. First Back TOC One-Dimensional Arrays Prev Next Last .2.2 Representation of Arrays in Memory In C++. any array is mapped to a contiguous memory location. The lowest address corresponds to the ﬁrst element. and the highest address to the last element. All memory elements reside next to each other.

for(j=0. Then the memory representation of array a looks like this: a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] 7 6 5 4 3 2 1 0 First Back TOC One-Dimensional Arrays Prev Next Last .Page 9 Chapter 10: Arrays and Strings © Christian Jacob Example: int a[8]. j<8. int j. j++) a[j] = 7-j.

max = 0.2.Page 10 Chapter 10: Arrays and Strings © Christian Jacob 10.h> int main() { int i. } First Back TOC One-Dimensional Arrays Prev Next Last . cout << “Maximum value: “ << max.3 Example: Finding the Maximum #include <iostream. int list[100]. return(0). i++) list[i] = rand(). i++) if(max < list[i]) max = list[i]. // initialize the array with random values for(i=0. i<100. i<100. // find maximum value for(i=0.

you have to do the assignments for each element: int i.4 No Array-to-Array Assignments You cannot assign one array to another in C++. // do something // assign all elements of array b to array a a = b. First Back TOC One-Dimensional Arrays Prev Next Last . // assign all elements of array b to array a for(i=0.illegal Instead. i++) a[i] = b[i]. // error -. b[10].Page 11 Chapter 10: Arrays and Strings © Christian Jacob 10. The following is illegal: int a[10].2. i<10.

Nothing will stop you from overrunning the end of an array: © You will assign values to some other variables´ data!!! © You might even write into a piece of the program code!!! First Back TOC One-Dimensional Arrays Prev Next Last .Page 12 Chapter 10: Arrays and Strings © Christian Jacob 10.2.5 No Bounds Checking C++ performs no bounds checking on arrays.

} First Back TOC One-Dimensional Arrays Prev Next Last . i++) crash[i] = i. i<100. return(1). Do not execute! int main() { int crash[10]. you can compile and run the following program.Page 13 Chapter 10: Arrays and Strings © Christian Jacob For example. i. even though the array crash is being overrun: // An incorrect program. for(i=0.

Specifying the size as 11 makes room for the null at the end of the string.3 Strings The most common use for one-dimensional arrays is to store strings of characters. one would write: char str[11]. ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ To declare an array str that could hold a 10-character string.Page 14 Chapter 10: Arrays and Strings © Christian Jacob 10. a string is deﬁned as a character array terminated by a null symbol ( ‘\0’ ). First Back TOC Strings Prev Next Last . In C++.

Page 15 Chapter 10: Arrays and Strings © Christian Jacob Some examples of string constants in C++ are: "hello there" "I like C++. ““. only contains the null terminator and represents the empty string." "#\$%§@@+*" "\"" "\"\"" "\\" "" The null string. First Back TOC Strings Prev Next Last .

Page 16 Chapter 10: Arrays and Strings © Christian Jacob 10. // read string from keyboard cout << “Here is your string: “. cout << str.} First Back TOC Strings Prev Next Last . the target of a cin stream. The following program reads (part of) a string entered by the user: #include <stdio.3.1 Reading a String from the Keyboard How to read a string entered from the keyboard? Make an array. that will receive the string. cin >> str.h> int main() { char str[80]. return(0). cout << “Enter a string: “.

gets(str). the above program only returns “This”. Solution: Use another C++ library function.} First Back TOC Strings Prev Next Last . Reason: The C++ input/output system stops reading a string when the ﬁrst whitespace character is encountered. gets().Page 17 Chapter 10: Arrays and Strings © Christian Jacob Problem: Entering the string “This is a test”. return(0). #include <iostream. not the entire sentence. // read a string from the keyboard cout << “Here is your string: “. cout << str << endl.h> int main() { char str[80]. // long enough for user input? cout << “Enter a string: “.h> #include <cstdio.

Page 18 Chapter 10: Arrays and Strings © Christian Jacob 10.2 Some C++ Library Functions for Strings C++ supports a range of string-manipulation functions.3. The most common are: • strcpy() : • strcat() : • strlen() : • strcmp() : copy characters from one string to another concatenation of strings length of a string comparison of strings First Back TOC Strings Prev Next Last .

Page 19 Chapter 10: Arrays and Strings © Christian Jacob strcpy(to_string.h> int main() { char a[10]. strcpy(a. cout << a. return(0).h> #include <cstring. } a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] h e l l o \0 ? ? ? ? First Back TOC Strings Prev Next Last . “hello”). from_string) — String Copy: #include <iostream.

h> int main() { char str[80].Page 20 Chapter 10: Arrays and Strings © Christian Jacob strlen(string) — String Length strlen(str) returns the length of the string pointed to by str. return(0). gets(str). cout << “Enter a string: “.} First Back TOC Strings Prev Next Last .h> #include <cstdio. #include <iostream. cout << “Length is: “ << strlen(str).e.h> #include <cstring.. the number of characters excluding the null terminator. i.

s2). strcpy(s1. “hello”).Page 21 Chapter 10: Arrays and Strings © Christian Jacob strcat(string_1. } First Back TOC Strings Prev Next Last . “ there”). return(0). s2[11]. cout << s1 << endl. int main() { char s1[21]. cout << s2 << endl. strcpy(s2.. strcat(s1. // includes . String s2 is unchanged.. string_2) — Concatenation of Strings The strcat() function appends s2 to the end of s1.

Page 22 Chapter 10: Arrays and Strings © Christian Jacob Output: hello there there First Back TOC Strings Prev Next Last .

Page 23 Chapter 10: Arrays and Strings © Christian Jacob Note: • The ﬁrst string array has to be large enough to hold both strings: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 h e l l o \0 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 0 1 2 3 4 5 6 7 8 9 10 ‘ ‘ t h e r e \0 ? ? ? ? s1: s2: strcat(s1.s2): 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 h e l l o ‘ ‘ t h e r e \0 ? ? ? ? ? ? ? ? ? • To be on the safe side: strlen(s1concats2) >= strlen(s1) + strlen(s2) First Back TOC Strings Prev Next Last .

string_2) — Comparison of Strings The strcmp(str_1. First Back TOC Strings Prev Next Last ...Page 24 Chapter 10: Arrays and Strings © Christian Jacob strcmp(string_1.e. according to dictionary order): a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd < . str_2) function compares two strings and returns the following result: • str_1 == str_2 • str_1 > str_2 • str_1 < str_2 : : : 0 positive number negative number The strings are compared lexicographically (i..

y ∈ Σ ) ( ∃( v 1. v 2 ∈ Σ ) ) ( ( a = wxv 1 ) ∧ ( b = wxv 2 ) ∧ ( x < y ) ) * * + First Back TOC Strings Prev Next Last . b ∈ Σ over an alphabet Σ . a<b :⇔ ∃( w ∈ Σ ) ∃( x.Page 25 Chapter 10: Arrays and Strings © Christian Jacob Lexicographical order: Given: Two words a. and an ordering relation “<“ on the elements of the alphabet.

\n”. gets(str).h> #include <cstdio.} else cout << “Logged on.h> int main() { char str[80].Page 26 Chapter 10: Arrays and Strings © Christian Jacob // Comparing strings #include <iostream. cout << “Enter password: “.\n”. return(0). “password”)) { // strings differ cout << “Invalid password.h> #include <cstring. if(strcmp(str. } First Back TOC Strings Prev Next Last .

Page 27 Chapter 10: Arrays and Strings © Christian Jacob 10. } First Back TOC Strings Prev Next Last . cout << str. for(i=0. i++) str[i] = toupper(str[i]). int main() { char str[80].. // Convert a string to uppercase // .. includes . str[i].3 Using the Null Terminator Operations on strings can be simpliﬁed using the fact that all strings are null-terminated. int i. return(0). “this is a test”). strcpy(str..3..

This corresponds to a table with 3 rows and 4 columns (for example).20 we would write: int matrix[3][4]. To declare a two-dimensional integer array two_dim of size 10.4 Two-Dimensional Arrays A two-dimensional array is a list of one-dimensional arrays. 0 0 1 2 1 2 3 Right Index 1 5 9 2 6 10 3 7 11 4 8 12 Left Index two_dim[1][2] First Back TOC Two-Dimensional Arrays Prev Next Last .Page 28 Chapter 10: Arrays and Strings © Christian Jacob 10.

h> int main() { int row=3. ++col) { matrix[row][col] = (row*4)+ col +1.Page 29 Chapter 10: Arrays and Strings © Christian Jacob We can generate the array above by using this program: #include <iostream. } cout << ‘\n’. row < 3. col < 4. ++row) { for(col=0. col=4. cout << matrix[row][col] << ‘ ‘. for(row=0. } return(0). int matrix[row][col].} First Back TOC Two-Dimensional Arrays Prev Next Last .

an integer array (with two-byte integers) with dimensions 100. The memory used to hold an array is required the entire time that the array is in existence.000 bytes. First Back TOC Two-Dimensional Arrays Prev Next Last .Page 30 Chapter 10: Arrays and Strings © Christian Jacob Memory Allocation for Two-Dimensional Arrays Storage for all array elements is determined at compile time. The following formula determines the number of bytes of memory that will be allocated: bytes = rows * columns * number_of_bytes_in_type For example.100 would require 100 * 100 * 2 = 20.

e.000 bytes are needed. i. This requires 4 * 10 * 20 = 800 bytes.5 Multidimensional Arrays C++ allows arrays with more than two dimensions. or a matrix of strings: char string_matrix[4][10][20]. First Back TOC Multidimensional Arrays Prev Next Last . If we scale the matrix by 10. then 80. to a 40 x 100 x 20 array. the following declaration creates a 4 x 10 x 20 character array.Page 31 Chapter 10: Arrays and Strings © Christian Jacob 10. The general form of an N-dimensional array declaration is: type array_name [size_1] [size_2] … [size_N]. For example.

i[0] will have the value 1. First Back TOC Array Initialization Prev Next Last .9..0: float i[10] = {1. and i[9] will have the value 10. The list-of-values has to be a comma-separated list of constants that are type-compatible with the base type of the array... Therefore..5.10}.6. In the following example.3.0.2.Page 32 Chapter 10: Arrays and Strings © Christian Jacob 10.8. a 10-element ﬂoat array is initialized with the numbers 1.0.0 through 10.4..6 Array Initialization The general form of array initialization is similar to that of other variables: type array-name[size] = { list-of-values }.7.

First Back TOC Array Initialization Prev Next Last . ‘\0’}. Remember that one has to make sure to make the array long enough to include the null terminator.1 Character Array Initialization Character arrays that will hold strings allow a shorthand initialization that takes this form: char array-name[size] = “string”. the following code fragment initializes str to the phrase “hello”: char str[6] = “hello”. This is the same as writing char str[6] = {‘h’. For example. ‘l’.6.Page 33 Chapter 10: Arrays and Strings © Christian Jacob 10. ‘l’. ‘o’. ‘e’.

4. 8. 16. For example. 6. 7. 49. 2. 9. 5. 3. the following code fragment initializes an array squares with the numbers 1 through 10 and their squares: int squares[9][2] = { 1.2 Multi-Dimensional Array Initialization Multi-dimensional arrays are initialized the same way as onedimensional arrays. 36. First Back TOC Array Initialization Prev Next Last . 1. 4. 9.Page 34 Chapter 10: Arrays and Strings © Christian Jacob 10. 25. 64.6. 81 }.

{5. {8. 49}. {9. especially for multi-dimensional arrays. 64}. The same declaration as above can also be written as: int squares[10][2] = { {1. 36}. {10. {3. 4}.Page 35 Chapter 10: Arrays and Strings © Christian Jacob For better readability. 25}. 100} }. 81}. 9}. {7. {2. 16}. 1}. {4. First Back TOC Array Initialization Prev Next Last . one can use subaggregate grouping by adding braces accordingly. {6.

} First Back TOC Array Initialization Prev Next Last . cin >> i.". return(0). j++) if(squares[j][1] == i) { cout << "Root: " << squares[j][0]. #include <iostream. cout << “Enter a number 1<=i<=100: “.Page 36 Chapter 10: Arrays and Strings © Christian Jacob The following program uses the squares array to ﬁnd the root of a number entered by the user. // look up i for(j=0.} cout << "No integer root. j.h> // declaration of squares array goes here int main() { int i. return(0). j<10.

So we can write: char errors[][20] = { “Divide by 0\n”. For a multi-dimensional array.3 Unsized Array Initializations It is possible to let C++ automatically dimension the arrays through the use of unsized arrays. char error_2[] = “End-of-File\n”. all but the leftmost dimension have to be speciﬁed.Page 37 Chapter 10: Arrays and Strings © Christian Jacob 10. First Back TOC Array Initialization Prev Next Last . “Access Denied\n” }. C++ will automatically create arrays large enough to hold all the initializers present. “End-of-File\n”. char error_3[] = “Access Denied\n”. char error_1[] = “Divide by 0\n”.6.

For example. • The size of the right index speciﬁes the maximum length of each string. First Back TOC Arrays of Strings Prev Next Last .Page 38 Chapter 10: Arrays and Strings © Christian Jacob 10. the following declares an array of 30 strings. • The size of the left index determines the number of strings. each having a maximum length of 80 characters (with one extra character for the null terminator): char string_array[30][81].7 Arrays of Strings An array of strings is a special form of a two-dimensional array.

The following example calls the gets() function with the third string in the array: gets(string_array[2]). First Back TOC Arrays of Strings Prev Next Last .Page 39 Chapter 10: Arrays and Strings © Christian Jacob For accessing an individual string. sixthString = string_array[5]. one simply speciﬁes only the left index: firstString = string_array[0].

t<100. gets(text[t]). t++) { cout << t << “: “. char text[100][80]. if(!text[t][0]) break. } // quit on blank line for(i=0.} First Back TOC Arrays of Strings Prev Next Last . i.Page 40 Chapter 10: Arrays and Strings © Christian Jacob This program accepts lines of text entered at the keyboard and redisplays them after a blank line is entered. // includes go here int main() { int t. i<t. return(0). for(t=0. i++) // redisplay the strings cout << text[i] << ‘\n’.

Page 41 Chapter 10: Arrays and Strings © Christian Jacob 10. One such application would be an employee database that stores • the name • telephone number • hours worked per pay period. // hours worked float wage[20]. // employee names int phone[20].8 An Example Using String Arrays Arrays of strings are commonly used for handling tables of information. // phone numbers float hours[20]. // wage First Back TOC An Example Using String Arrays Prev Next Last . These data we could store in arrays: char name[20][80]. and • hourly wage.

cin >> phone[i].1 Entering Information void enter() { int i. } } First Back TOC An Example Using String Arrays Prev Next Last . cout << “Phone number: “. i<20. i++) { cout << “Last name: “. for(i=0.Page 42 Chapter 10: Arrays and Strings © Christian Jacob 10. cin >> wage[i]. cout << “Wage: “. cin >> name[i].8. cout << “Hours worked: “. cin >> hours[i].

i++) { cout << "Name: " << name[i] << " / " << "phone: " << phone[i] << ‘\n’.8. cout << “Pay for the week: “. i < 20. cout << ‘\n’.2 Displaying Database Contents void report() { int i. for(i=0.Page 43 Chapter 10: Arrays and Strings © Christian Jacob 10. cout << wage[i] * hours[i]. } } First Back TOC An Example Using String Arrays Prev Next Last .

cout << “1. Quit\n”. Enter information\n”.8. } First Back TOC An Example Using String Arrays Prev Next Last . return choice.3 Menu For User´s Selection int menu() { int choice. cin >> choice. cout << “\n”. cout << “2. Report information\n”. cout << “0. cout << “Choose one: “.Page 44 Chapter 10: Arrays and Strings © Christian Jacob 10.

default: cout << “Try again. } First Back TOC An Example Using String Arrays Prev Next Last . break. // get selection switch(choice) { case 0: break.4 Main Function int main() { int choice. break. } } while( choice != 0).\n\n”. do { choice = menu(). case 2: report().Page 45 Chapter 10: Arrays and Strings © Christian Jacob 10. case 1: enter(). return(0).8.

. int main() { . void report(). void enter()..5 Putting It All Together #include <iostream...... } void report() { . } First Back TOC An Example Using String Arrays Prev Next Last .Page 46 Chapter 10: Arrays and Strings © Christian Jacob 10. } int menu() { .8.h> // array declarations int menu(). } void enter() { ..

1998. Boston. 1998. Berkeley. The Universal Machine. C++ from the Ground Up. Barnes.9 References • Schildt. McGraw-Hill.Page 47 Chapter 10: Arrays and Strings © Christian Jacob 10. MA: WCB/ McGraw-Hill. Chapter 11. H. • G. First Back TOC References Prev Next Last .. Blank and R. Chapter 5.