Chapter 1
Chapter 1
Chapter 1
1
variables each one with a different identifier. Instead of that, using an array we can store 10
different values of the same type, int for example, with a unique identifier.
But additionally, when we declare an Array, we have the possibility to assign initial
values to each one of its elements using curly brackets { } .
For example: int day [5] = { 16, 2, 77, 40, 12071 };
The above declaration would have created an array like the following one:
The number of elements in the array that we initialized within curly brackets { } must be
equal or less than the length in elements that we declared for the array enclosed within
square brackets [ ]. If we have less number of items for the initialization, the rest will be
filled with zero.
For example, in the example of the day array we have declared that it had 5 elements and
in the list of initial values within curly brackets { } we have set 5 different values, one
for each element. If we ignore the last initial value (12071) in the above initialization, 0
will be taken automatically for the last array element.
Because this can be considered as useless repetition, C++ allows the possibility of
leaving empty the brackets [ ], where the number of items in the initialization bracket
will be counted to set the size of the array.
int day [] = { 1, 2, 7, 4, 12,9 };
The compiler will count the number of initialization items which is 6 and set the size of
the array day to 6 (i.e.: day[6])
You can use the initialization form only when defining the array. You cannot use it later,
and cannot assign one array to another once. i.e.
2
int ar [4];
ar[]={1,2,3,4};//not allowed
arr=ar;//not allowed
Note: when initializing an array, we can provide fewer values than the array elements.
E.g. int a [10] = {10, 2, 3}; in this case the compiler sets the remaining elements to zero.
For example, to store the value 75 in the third element of the array variable day a suitable
sentence would be: day[2] = 75; //as the third element is found at index 2
And, for example, to pass the value of the third element of the array variable day to the
variable a , we could write: a = day[2];
Therefore, for all the effects, the expression day[2] is like any variable of type int with
the same properties. Thus an array declaration enables us to create a lot of variables of
the same type with a single declaration and we can use an index to identify individual
elements.
Notice that the third element of day is specified day[2], since first is day[0], second
day[1] , and therefore, third is day[2] . By this same reason, its last element is day [4].
Since if we wrote day [5], we would be acceding to the sixth element of day and
therefore exceeding the size of the array. This might give you either error or unexpected
value depending on the compiler.
We must take care of not confusing these two possible uses of brackets [ ] with arrays:
Example:
int day[5]; // declaration of a new Array (begins with a type name)
day[2] = 75; // access to an element of the Array.
Other valid operations with arrays in accessing and assigning:
int a=1;
3
day [0] = a;
day[a] = 5;
b = day [a+2];
day [day[a]] = day [2] + 5; day [day[a]] = day[2] + 5;
- Matrix represents a bi-dimensional array of 3 per 5 values of type int. The way to declare
this array would be:
int matrix[3][5];
- For example, the way to reference the second element vertically and fourth horizontally in
an expression would be:
matrix[1][3]
- Multidimensional arrays are not limited to two indices (two dimensions). They can contain
so many indices as needed, although it is rare to have to represent more than 3 dimensions.
4
For example, the following array (or string of characters) can store a string up to 20 characters
long. You may imagine it thus: char name [20];
Name
This maximum size of 20 characters is not required to be always fully used. For example,
name could store at some moment in a program either the string of characters "Hello" or the
string "studying C++”. Therefore, since the array of characters can store shorter strings than
its total length, there has been reached a convention to end the valid content of a string with a
null character, whose constant can be written as '\0’.
We could represent name (an array of 20 elements of type char) storing the strings of
characters "Hello" and "Studying C++" in the following way:
Notice how after the valid content it is included a null character ('\0') in order to indicate the
end of string. The empty cells (elements) represent indeterminate values.
Initialization of Strings
Because strings of characters are ordinary arrays they fulfill same rules as any array. For
example, if we want to initialize a string of characters with predetermined values we can do it
in a similar way to any other array:
char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared a string of characters (array) of 6 elements of type char
initialized with the characters that compose Hello plus a null character '\0' .
Nevertheless, string of characters have an additional way to initialize its values: using
constant strings. Strings of characters are specified enclosed between double quotes ( “ “ ),
Eg: "the result is: " is a constant string that we have probably used in some occasion. Unlike
single quotes ( ' ) which allow to specify single character constants, double quotes ( " ) are
constants that specify a succession of characters. These strings enclosed between double
quotes have always a null character ( '\0' ) automatically appended at the end.
Therefore we could initialize the string mystring with values by any of these two ways:
char mystring[] = {'H', 'e', 'l', 'l', 'o', '\0'};
char mystring [] = "Hello";
In both cases the Array or string of characters mystring is declared with a size of 6 characters
(elements of type char ): the 5 characters that compose Hello plus a final null character ( '\0' )
which specifies the end of the string and that, in the second case, when using double quotes
5
( " ) it is automatically appended.
Assigning Values to Strings
Just like any other variables, array of character can store values using assignment operators.
But the following is not allowed.
mystring=”Hello”;
This is allowed only during initialization. Therefore, since the value of an assignation can
only be an element of an array and not the entire array, what would be valid is to assign a
string of characters to an array of char using a method like this:
mystring[0] = 'H'; mystring[3] = 'l';
mystring[1] = 'e'; mystring[4] = 'o';
mystring[2] = 'l'; mystring[5] = '\0';
But as you may think, this does not seem to be a very practical method. Generally for
assigning values to an array, and more specifically to a string of characters, a series of
functions like strcpy are used. strcpy (string copy) is defined in the (string.h) library and can
be called the following way:
strcpy ( string1 , string2 );
This does copy the content of string2 into string1 . string2 can be either an array, a pointer, or
a constant string, so the following line would be a valid way to assign the constant string
"Hello" to mystring :
strcpy (mystring, "Hello");
Functions to manipulate strings
The cstring library(string.h) defines many functions to perform some manipulation operations
with C-like strings (like already explained strcpy). Here you have a brief with the most usual:
a) String length
Returns the length of a string, not including the null character (\0).
strlen (const char* string );
b) String Concatenation:
Appends src string at the end of dest string. Returns dest.
The string concatenation can have two forms, where the first one is to append the whole
content of the source to the destination the other will append only part of the source to the
destination.
Appending the whole content of the source
strcat (char* dest , const char* src );
Appending part of the source
strncat (char* dest , const char* src, int size );
Where size is the number characters to be appended
6
c) String Copy:
Overwrites the content of the dest string by the src string. Returns dest. The string copy can
have two forms, where the first one is to copying the whole content of the source to the
destination and the other will copy only part of the source to the destination.
Copy the whole content of the source
strcpy (char* dest , const char* src );
Appending part of the source
strncpy (char* dest , const char* src, int size );
Where size is the number characters to be copied
d) String Compare:
Compares the two string string1 and string2. The string compare can have two forms, where
the first one is to compare the whole content of the two strings and the other will compare
only part of the two strings.
Copy the whole content of the source
strcmp (const char* string, const char* string2 );
Appending part of the source
strncmp (const char* string1, const char* string2, int size);
Where size is the number characters to be compared
Both string compare functions returns three different values:
Returns 0 is the strings are equal
Returns negative value if the first is less than the second string
Returns positive value if the first is greater than the second string