chapter 5. arrays and strings
TRANSCRIPT
Chapter 5. ARRAY AND STRING
Chapter 5. ARRAY AND STRING
Minh Quang NGUYEN
Hanoi National University of Education
September 2015
Paris Saclay Minh Quang NGUYEN 1
Chapter 5. ARRAY AND STRING
ARRAYs
STRING
Two-Dimensional Arrays
Initialization
You do it
Q & A
Paris Saclay Minh Quang NGUYEN 2
Chapter 5. ARRAY AND STRING
ARRAYs
What is array?
I An array is a collection of variables of the same type that arereferred to by a common name.
I Every member of an array is allocated together in a memorylocation.
Paris Saclay Minh Quang NGUYEN 3
Chapter 5. ARRAY AND STRING
ARRAYs
What is array?
I An array is a collection of variables of the same type that arereferred to by a common name.
I Every member of an array is allocated together in a memorylocation.
Paris Saclay Minh Quang NGUYEN 4
Chapter 5. ARRAY AND STRING
ARRAYs
What is array?
I An array is a collection of variables of the same type that arereferred to by a common name.
I Every member of an array is allocated together in a memorylocation.
Paris Saclay Minh Quang NGUYEN 5
Chapter 5. ARRAY AND STRING
ARRAYs
One-Dimensional Arrays
A one-dimensional array is a list of related variables. The generalform of a one-dimensional array declaration is:
type variable_name[size];
wheretype: base type of the array, determines the data type of eachelement in the arrayvariable name: the name of the arraysize: how many elements the array will hold
Paris Saclay Minh Quang NGUYEN 6
Chapter 5. ARRAY AND STRING
ARRAYs
Example
Declaration withoutinitialization
int sample[10];
float float_numbers[100];
char last_name[40];
Declaration with initialization
int scores[7] = {1, 3, 4, 5,
1, 3, 2};
char alphabet[3] = {’A’, ’B’,
’E’};
Paris Saclay Minh Quang NGUYEN 7
Chapter 5. ARRAY AND STRING
ARRAYs
Accessing Array Elements
I An individual element within an array is accessed by use of anindex. An index describes the position of an element within anarray.
I This consists of the name of the array, followed by bracketsdelimiting a integer or a variable i.
Example
score[1] = 9;
for(int i = 0; i < 7; i++)
cout << score[i] << endl;
Note: In C++ the first element has the index zero!
Paris Saclay Minh Quang NGUYEN 8
Chapter 5. ARRAY AND STRING
ARRAYs
Accessing Array Elements
I An individual element within an array is accessed by use of anindex. An index describes the position of an element within anarray.
I This consists of the name of the array, followed by bracketsdelimiting a integer or a variable i.
Example
score[1] = 9;
for(int i = 0; i < 7; i++)
cout << score[i] << endl;
Note: In C++ the first element has the index zero!
Paris Saclay Minh Quang NGUYEN 9
Chapter 5. ARRAY AND STRING
ARRAYs
Accessing Array Elements
I An individual element within an array is accessed by use of anindex. An index describes the position of an element within anarray.
I This consists of the name of the array, followed by bracketsdelimiting a integer or a variable i.
Example
score[1] = 9;
for(int i = 0; i < 7; i++)
cout << score[i] << endl;
Note: In C++ the first element has the index zero!
Paris Saclay Minh Quang NGUYEN 10
Chapter 5. ARRAY AND STRING
ARRAYs
No Array-to-Array Assignments
You cannot assign one array to another in C++.
Example
int a[10], b[10];
// do something
// assign all elements
// of array b to array a
a = b;
Instead, you have to do theassignments for each element
int i;
// assign all elements
// of array b to array a
for(i=0; i<10; i++)
a[i] = b[i];
Or copy all of the memory bytes
memcpy();
Paris Saclay Minh Quang NGUYEN 11
Chapter 5. ARRAY AND STRING
ARRAYs
No Array-to-Array Assignments
You cannot assign one array to another in C++.
Example
int a[10], b[10];
// do something
// assign all elements
// of array b to array a
a = b;
Instead, you have to do theassignments for each element
int i;
// assign all elements
// of array b to array a
for(i=0; i<10; i++)
a[i] = b[i];
Or copy all of the memory bytes
memcpy();
Paris Saclay Minh Quang NGUYEN 12
Chapter 5. ARRAY AND STRING
ARRAYs
No Bounds Checking
C++ performs no bounds checking on arrays. Nothing will stopyou from overrunning the end of an array.
I You will assign values to some other variables’ data!
I You might even write into a piece of the program code!
Example
int crash[10], i;
for(i = 0; i < 11; i++)
crash[i] = i;
Paris Saclay Minh Quang NGUYEN 13
Chapter 5. ARRAY AND STRING
STRING
What is string?
The most common use for one-dimensional arrays is to storestrings of characters.In C++, a string is defined as a character array terminated by anull symbol.
Paris Saclay Minh Quang NGUYEN 14
Chapter 5. ARRAY AND STRING
STRING
Declaration
I To declare an array str that could hold a 10-character string,one would write:char str[11];
I Specifying the size as 10 makes room for the null at the endof the string.
Paris Saclay Minh Quang NGUYEN 15
Chapter 5. ARRAY AND STRING
STRING
Declaration
I To declare an array str that could hold a 10-character string,one would write:char str[11];
I Specifying the size as 10 makes room for the null at the endof the string.
Paris Saclay Minh Quang NGUYEN 16
Chapter 5. ARRAY AND STRING
STRING
Declaration
I To declare an array str that could hold a 10-character string,one would write:char str[11];
I Specifying the size as 10 makes room for the null at the endof the string.
Paris Saclay Minh Quang NGUYEN 17
Chapter 5. ARRAY AND STRING
STRING
Reading a String from the Keyboard
Make an array, that will receive the string, the target of a cinstream.
cout << "Enter a string: ";
cin >> str;
cout << "Your string:";
cout << str;
Paris Saclay Minh Quang NGUYEN 18
Chapter 5. ARRAY AND STRING
STRING
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions
I strcpy(): copy characters from one string to another
I strcat(): concatenation of strings
I strlen(): length of a string
I strcmp(): comparison of strings
Paris Saclay Minh Quang NGUYEN 19
Chapter 5. ARRAY AND STRING
STRING
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions
I strcpy(): copy characters from one string to another
I strcat(): concatenation of strings
I strlen(): length of a string
I strcmp(): comparison of strings
Paris Saclay Minh Quang NGUYEN 20
Chapter 5. ARRAY AND STRING
STRING
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions
I strcpy(): copy characters from one string to another
I strcat(): concatenation of strings
I strlen(): length of a string
I strcmp(): comparison of strings
Paris Saclay Minh Quang NGUYEN 21
Chapter 5. ARRAY AND STRING
STRING
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions
I strcpy(): copy characters from one string to another
I strcat(): concatenation of strings
I strlen(): length of a string
I strcmp(): comparison of strings
Paris Saclay Minh Quang NGUYEN 22
Chapter 5. ARRAY AND STRING
STRING
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions
I strcpy(): copy characters from one string to another
I strcat(): concatenation of strings
I strlen(): length of a string
I strcmp(): comparison of strings
Paris Saclay Minh Quang NGUYEN 23
Chapter 5. ARRAY AND STRING
STRING
Example: strcpy() and strlen()
Example 1: strcpy()
char a[10];
strcpy(a, "hello");
Example 2: strlen()
cout << "Enter a string: ";
gets(str);
cout << "Length is: " << strlen(str);
Figure: Result of example 1
Paris Saclay Minh Quang NGUYEN 24
Chapter 5. ARRAY AND STRING
STRING
Example: strcat()
Example 3: strcpy()
char s1[21], s2[11];
strcpy(s1, "hello");
strcpy(s2, " there");
strcat(s1, s2);
The first string array has to belarge enough to hold bothstrings:
Paris Saclay Minh Quang NGUYEN 25
Chapter 5. ARRAY AND STRING
STRING
About strcmp()
The strcmp(str1, str2)
function compares two stringsand returns the following result:
I str1 == str2: 0
I str1 > str2 : positivenumber
I str1 < str2 : negativenumber
The strings are comparedlexicographically (i.e., accordingto dictionary order):
a < aa < aaa < . . . < b < ba < bb < . . . < bz < baa < . . . < abca < abd < ...
Example 4
cout << "Enter password: ";
gets(str);
if(strcmp(str, "password"))
{
cout << "Invalid password.\n";
}
else
cout << "Logged on.\n";
Paris Saclay Minh Quang NGUYEN 26
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Two-Dimensional Arrays: declaration
I A two-dimensional array isa list of one-dimensionalarrays.
I To declare atwo-dimensional integerarray two dim of size 10,20we would write:int matrix[3][4];
I This corresponds to a tablewith 3 rows and 4 columns
Paris Saclay Minh Quang NGUYEN 27
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Memory Allocation for Two-Dimensional Arrays
C++ supports a range of string-manipulation functions
I Storage for all array elements is determined at compile time.
I The memory used to hold an array is required the entire timethat the array is in existence.
I The following formula determines the number of bytes ofmemory that will be allocated:bytes = rows × columns × number of bytes in type
I For example, an integer array (with two-byte integers) withdimensions 100,100 would require 100 * 100 * 2 = 20,000bytes.
Paris Saclay Minh Quang NGUYEN 28
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Memory Allocation for Two-Dimensional Arrays
C++ supports a range of string-manipulation functions
I Storage for all array elements is determined at compile time.
I The memory used to hold an array is required the entire timethat the array is in existence.
I The following formula determines the number of bytes ofmemory that will be allocated:bytes = rows × columns × number of bytes in type
I For example, an integer array (with two-byte integers) withdimensions 100,100 would require 100 * 100 * 2 = 20,000bytes.
Paris Saclay Minh Quang NGUYEN 29
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Memory Allocation for Two-Dimensional Arrays
C++ supports a range of string-manipulation functions
I Storage for all array elements is determined at compile time.
I The memory used to hold an array is required the entire timethat the array is in existence.
I The following formula determines the number of bytes ofmemory that will be allocated:bytes = rows × columns × number of bytes in type
I For example, an integer array (with two-byte integers) withdimensions 100,100 would require 100 * 100 * 2 = 20,000bytes.
Paris Saclay Minh Quang NGUYEN 30
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Memory Allocation for Two-Dimensional Arrays
C++ supports a range of string-manipulation functions
I Storage for all array elements is determined at compile time.
I The memory used to hold an array is required the entire timethat the array is in existence.
I The following formula determines the number of bytes ofmemory that will be allocated:bytes = rows × columns × number of bytes in type
I For example, an integer array (with two-byte integers) withdimensions 100,100 would require 100 * 100 * 2 = 20,000bytes.
Paris Saclay Minh Quang NGUYEN 31
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Memory Allocation for Two-Dimensional Arrays
C++ supports a range of string-manipulation functions
I Storage for all array elements is determined at compile time.
I The memory used to hold an array is required the entire timethat the array is in existence.
I The following formula determines the number of bytes ofmemory that will be allocated:bytes = rows × columns × number of bytes in type
I For example, an integer array (with two-byte integers) withdimensions 100,100 would require 100 * 100 * 2 = 20,000bytes.
Paris Saclay Minh Quang NGUYEN 32
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Multidimensional Arrays
C++ supports a range of string-manipulation functions
I C++ allows arrays with more than two dimensions. Thegeneral form of an N-dimensional array declaration is:type array name [size 1] [size 2] ... [size N];
I For example, the following declaration creates a 4 characterarray, or a matrix of strings:char string matrix[4][10][20];
Paris Saclay Minh Quang NGUYEN 33
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Multidimensional Arrays
C++ supports a range of string-manipulation functions
I C++ allows arrays with more than two dimensions. Thegeneral form of an N-dimensional array declaration is:type array name [size 1] [size 2] ... [size N];
I For example, the following declaration creates a 4 characterarray, or a matrix of strings:char string matrix[4][10][20];
Paris Saclay Minh Quang NGUYEN 34
Chapter 5. ARRAY AND STRING
Two-Dimensional Arrays
Multidimensional Arrays
C++ supports a range of string-manipulation functions
I C++ allows arrays with more than two dimensions. Thegeneral form of an N-dimensional array declaration is:type array name [size 1] [size 2] ... [size N];
I For example, the following declaration creates a 4 characterarray, or a matrix of strings:char string matrix[4][10][20];
Paris Saclay Minh Quang NGUYEN 35
Chapter 5. ARRAY AND STRING
Initialization
Character Array InitializationC++ supports a range of string-manipulation functions
I Character arrays that will hold strings allow a shorthandinitialization that takes this form:char array-name[size] = "string";
I For example, the following code fragment initializes str to thephrase ”hello”:char str[6] = "hello";
I This is the same as writing:char str[6] = ’h’, ’e’, ’l’, ’l’, ’o’, ’
0’;
Note: Remember that one has to make sure to make the arraylong enough to include the null terminator.
Paris Saclay Minh Quang NGUYEN 36
Chapter 5. ARRAY AND STRING
Initialization
Character Array InitializationC++ supports a range of string-manipulation functions
I Character arrays that will hold strings allow a shorthandinitialization that takes this form:char array-name[size] = "string";
I For example, the following code fragment initializes str to thephrase ”hello”:char str[6] = "hello";
I This is the same as writing:char str[6] = ’h’, ’e’, ’l’, ’l’, ’o’, ’
0’;
Note: Remember that one has to make sure to make the arraylong enough to include the null terminator.
Paris Saclay Minh Quang NGUYEN 37
Chapter 5. ARRAY AND STRING
Initialization
Character Array InitializationC++ supports a range of string-manipulation functions
I Character arrays that will hold strings allow a shorthandinitialization that takes this form:char array-name[size] = "string";
I For example, the following code fragment initializes str to thephrase ”hello”:char str[6] = "hello";
I This is the same as writing:char str[6] = ’h’, ’e’, ’l’, ’l’, ’o’, ’
0’;
Note: Remember that one has to make sure to make the arraylong enough to include the null terminator.
Paris Saclay Minh Quang NGUYEN 38
Chapter 5. ARRAY AND STRING
Initialization
Character Array InitializationC++ supports a range of string-manipulation functions
I Character arrays that will hold strings allow a shorthandinitialization that takes this form:char array-name[size] = "string";
I For example, the following code fragment initializes str to thephrase ”hello”:char str[6] = "hello";
I This is the same as writing:char str[6] = ’h’, ’e’, ’l’, ’l’, ’o’, ’
0’;
Note: Remember that one has to make sure to make the arraylong enough to include the null terminator.
Paris Saclay Minh Quang NGUYEN 39
Chapter 5. ARRAY AND STRING
Initialization
Character Array InitializationC++ supports a range of string-manipulation functions
I Character arrays that will hold strings allow a shorthandinitialization that takes this form:char array-name[size] = "string";
I For example, the following code fragment initializes str to thephrase ”hello”:char str[6] = "hello";
I This is the same as writing:char str[6] = ’h’, ’e’, ’l’, ’l’, ’o’, ’
0’;
Note: Remember that one has to make sure to make the arraylong enough to include the null terminator.
Paris Saclay Minh Quang NGUYEN 40
Chapter 5. ARRAY AND STRING
Initialization
Multi-Dimensional Array Initialization
I Multi-dimensional arrays are initialized the same way asonedimensional arrays
I For example, the following code fragment initializes an arraysquares with the numbers 1 through 10 and their squares:int squares[10][2] = {{1, 1}, {2, 4}, {3, 9}, {4, 16},{5, 25}, {6, 36}, {7, 49}, {8, 64}, {9, 81}, {10,100}};
Paris Saclay Minh Quang NGUYEN 41
Chapter 5. ARRAY AND STRING
Initialization
Multi-Dimensional Array Initialization
I Multi-dimensional arrays are initialized the same way asonedimensional arrays
I For example, the following code fragment initializes an arraysquares with the numbers 1 through 10 and their squares:int squares[10][2] = {{1, 1}, {2, 4}, {3, 9}, {4, 16},{5, 25}, {6, 36}, {7, 49}, {8, 64}, {9, 81}, {10,100}};
Paris Saclay Minh Quang NGUYEN 42
Chapter 5. ARRAY AND STRING
Initialization
Multi-Dimensional Array Initialization
I Multi-dimensional arrays are initialized the same way asonedimensional arrays
I For example, the following code fragment initializes an arraysquares with the numbers 1 through 10 and their squares:int squares[10][2] = {{1, 1}, {2, 4}, {3, 9}, {4, 16},{5, 25}, {6, 36}, {7, 49}, {8, 64}, {9, 81}, {10,100}};
Paris Saclay Minh Quang NGUYEN 43
Chapter 5. ARRAY AND STRING
Initialization
Unsized Array Initializations
I It is possible to let C++ automatically dimension the arraysthrough the use of unsized arrays. C++ will automaticallycreate arrays large enough to hold all the initializers present.char error1[] = "Divide by 0";
char error2[] = "End-of-File";
char error3[] = "Access Denied";
I For a multi-dimensional array, all but the leftmost dimensionhave to be specified. So we can write:char errors[][20] = {"Divide by 0", "End-of-File",
"Access Denied" };
Paris Saclay Minh Quang NGUYEN 44
Chapter 5. ARRAY AND STRING
Initialization
Unsized Array Initializations
I It is possible to let C++ automatically dimension the arraysthrough the use of unsized arrays. C++ will automaticallycreate arrays large enough to hold all the initializers present.char error1[] = "Divide by 0";
char error2[] = "End-of-File";
char error3[] = "Access Denied";
I For a multi-dimensional array, all but the leftmost dimensionhave to be specified. So we can write:char errors[][20] = {"Divide by 0", "End-of-File",
"Access Denied" };
Paris Saclay Minh Quang NGUYEN 45
Chapter 5. ARRAY AND STRING
Initialization
Unsized Array Initializations
I It is possible to let C++ automatically dimension the arraysthrough the use of unsized arrays. C++ will automaticallycreate arrays large enough to hold all the initializers present.char error1[] = "Divide by 0";
char error2[] = "End-of-File";
char error3[] = "Access Denied";
I For a multi-dimensional array, all but the leftmost dimensionhave to be specified. So we can write:char errors[][20] = {"Divide by 0", "End-of-File",
"Access Denied" };
Paris Saclay Minh Quang NGUYEN 46
Chapter 5. ARRAY AND STRING
Initialization
Arrays of Strings
I An array of strings is a special form of a two-dimensionalarray.
I The size of the left index determines the number of strings.I The size of the right index specifies the maximum length of
each string.
For example, the following declares an array of 30 strings, eachhaving a maximum length of 80 characters (with one extracharacter for the null terminator):char string array[30][81];
Paris Saclay Minh Quang NGUYEN 47
Chapter 5. ARRAY AND STRING
You do it
Paris Saclay Minh Quang NGUYEN 48
Chapter 5. ARRAY AND STRING
Q & A
QUESTION and ANSWER
Paris Saclay Minh Quang NGUYEN 49