Chapter 4
Arrays, Strings and Pointers
5. What is Array
An array is a series of elements of the same type placed in contiguous memory
location that can be individually referenced by adding an index to a unique
identifier.
An array is a collection of data structure that stores elements/ items that have
the same data type.
An array element is identified and accessed by its own unique index (or
subscript).
The index must be an integer and indicates the position of the element in the
array
In C++ the index of the first array element is 0 and the last element is N-1,
where N is the size of the array.
5.1. Properties of arrays:
Arrays in C++ are zero-bounded; that is the index of the first element in the array
is 0 and the last element is N-1, where N is the size of the array.
It is illegal to refer to an element outside of the array bounds.
Array can only hold values of one type.
5.2. Array declaration:
The array must be declared before one uses it like other variables.
In the array declaration one must define:
o The type of the array (i.e. integer, floating point, char etc.)
o Name of the array,
o The total number of memory locations to be allocated or the number of
elements in the array.
General syntax:
dataType arrayName [arraySize];
Note: array size cannot be a variable whose value is set while the program is
running.
E.g: To declare an integer with size of 10 having a name of num is:
int num[10]; // ten consecutive memory locations will be reserved
char name[20]; //allocate 20 consecutive char variables in memory
5.3. Initializing Arrays:
Means assigning a specific values for the array during declaration by enclosing
those initial values in braces { }.
E.g: int day[5] = {16, 2, 77, 40, 120};
The above declaration would have created an array like the following one:
0 1 2 3 4
day 16 2 77 40 120
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.
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. That means:
int arr[ ] = {16, 2, 77, 40, 12};
int ar[4];
ar[ ] = {1,2,3,4}; //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.
5.4. Accessing and processing array elements:
The values of any of the elements in an array can be accessed like the value of a
regular variable of the same type.
General syntax:
arrayName [index];
In C++ the first element has an index of 0 and the last element has an index, which is one
less the size of the array (i.e. arraysize-1). Thus, from the above declaration, day[0] is the
first element and day[4] is the last element.
E.g: The following statement stores the value 75 in the third element of day:
day[2] = 75;
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];
Given the declaration int mark[5] = {19,15,8,10,20};
Find the value of mark[0], mark[1], mark[2], mark[3], mark[4]?
mark[0] = 19 mark[2] = 8
mark[1] = 15 mark[3] = 10 mark[5] = 20
At this point it is important to be able to clearly distinguish between the two uses the
square brackets [ ] have for arrays.
o One is to set the size of arrays during declaration.
o The other is to specify indices for a specific array element when accessing the
elements of the array.
E.g: int day[5]; //declaration of new array
day[2] = 75; //accessing to an element of the array
Other valid operations with arrays in accessing and assigning:
int a=1;
day [0] = a;
day[a] = 5;
b = day [a+2];
day [day[a]] = day [2] + 5;
To insert/read values into an array:
cout<<”Enter Array Elements”;
for(i=0;i<10);i++){
cin>> Array[i];
}
And the elements can be increased by 5:
Array[i] = Array[i] + 5; or Array[i] += 5;
Array elements can form part of the condition for if statement:
if (max<numbers[j])
{
max= numbers[j];
}
For loops are the usual means of accessing every element in an array:
for (i = 0; i < MAX; i++)
{
cin>>numbers[i];
}
E.g: A program that finds the sum and average of array elements:
#include<iostream.h>
int main()
{
int numbers[ ] ={ 10,20,30,40,50}; //array declaration & initialization
float sum = 0, average; // declaring variables that store sum and average of array elements
for (int i = 0; i <5; i++)
{
sum += numbers[i];
average = sum / 5;
}
cout<<”The Sum of Array Elements=”<<sum;
cout<<”The Average of Array Elements=”<<average;
return 0;
}
Displaying Arrays:
int numbers[5]={10,20,30,40,50};
cout<<”\nList of Array Elements\n”;
for(i=0;i<5;i++)
{
cout<<numbers[i];
}
Two dimensional Arrays:
It is the simplest form of the multidimensional array.
Declaration:
type arrayName [number of rows][number of columns];
Initialization:
int x [2][3]={{2,3,4},{5,7,6}};
Index 0 1 2
2 3 4
5 6 7
Accessing: An element in 2-dimensional array is accessed by using the indexes,
i.e., row index and column index of the array.
E.g: x [0][1] = 3;
#include<iostream.h>
int main( ) {
int a[5] [2] = { {0,0}, {1,2}, {2,4}, {3,6}, {4,8} }; //arrays of 5 rows and 2 columns
for ( int i = 0; i < 5; i++ )
{
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "] [" << j << "]: ";
cout << a[ i ][ j ]<< endl;
}
}
return 0;
}
5.5. Strings representation and manipulation
There are two types of strings commonly used in C++ programming language.
1. Strings that are objects of string class (the standard C++ library string
class).
2. C-strings(c-style strings).
C-strings: - in c programming, the collection of characters is stored in the form of arrays.
This is also supported in C++ programming. Hence it‟s called c-strings.
C-string are arrays of type char terminated with null character that is \0 (ASCII
value of null character is 0;
How to define a c-string?
char str[ ] = “C++”;
Alternative ways of defining a string:
char str[4] = “C++”;
char str[ ] = { „C‟, „+‟, „+‟, „\0‟ };
char str[4] = { „C‟, „+‟, „+‟, „\0‟ };
Like arrays, it is not necessary to use all the space allocated for the string.
Example: char str[100] = “ C++”;
#include<iostream.h>
int main( )
{
char str[100];
cout<<”Enter a string: “;
cin>>str;
cout<<”you entered: “<str<<endl;
return 0;
}
String of characters:
String in C++ is a sequence of character in which the last character is the null character „\0‟.
The null character indicates the end of the string.
Any array of character can be converted into string type in C++ by appending this
special/null character„\0‟at the end of the array sequence.
Hence if a string has n characters then it requires an n+1 element array (at least) to store
it.
For example, the following array (or string of characters) can store a string up to 10
characters long. You may imagine it thus:
char name [10];
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:
name
H e l l o \0
S t u d y i n g C + + \0
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.
5.6. 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.
In the expressions we have used in examples of previous chapters there have
already appeared several times constants that represented entire strings of
characters. These are specified enclosed between double quotes ( “ “ ), for example:
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 ( " ) it is automatically appended.
Before going further, you should note that the assignation of multiple constants like
double-quoted constants ( " ) to arrays are only valid when initializing the array,
that is, at the moment when declared.
The following expressions within a code are not valid for arrays
mystring = "Hello";
mystring[ ] = "Hello";
neither would be: mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };
So remember: We can "assign" a multiple constant to an Array only at the moment
of initializing it. The reason will be more comprehensible when you know a bit
more about pointers, since then it will be clarified that an array is simply a constant
pointer pointing to an allocated block of memory. And because of this constant
feature, the array itself cannot be assigned any value, but we can assign values to
each of the elements of the array.
At the moment of initializing an Array it is a special case, since it is not an
assignation, although the same equal sign (=) is used. Anyway, have always present
the rule previously underlined.
5.7. Assigning Values to Strings
o Just like any other variables, array of character can store values using assignment
operators. But the following is not allowed.
mystring = ”Hello”;
o 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[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';
o 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 ( str ing c o py ) is defined in the ( string.h ) library
and can be called the following way:
strcpy ( string1 , string2 );
o 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");
For example:
#include<iostream.h>
#include<string.h>
int main ()
{
char MyName [20];
strcpy (MyName,"Abebe");
cout << MyName;
return 0;
}
o Another frequently used method to assign values to an array is by using directly the input
stream ( cin ). In this case the value of the string is assigned by the user during program
execution.
o When cin is used with strings of characters it is usually used with its getline method, that
can be called following this prototype:
o cin.getline ( char buffer [ ], int length , char delimiter = ' \n');
o where buffer is the address where to store the input (like an array, for example), length is
the maximum length of the buffer (the size of the array) and delimiter is the character
used to determine the end of the user input, which by default - if we do not include that
parameter - will be the newline character ( '\n' ).
#include<iostream.h>
#include<string.h>
int main ( ) {
char mybuffer [100];
cout << "What's your name? ";
cin.getline (mybuffer, 100);
cout << "Hello " << mybuffer << ".\n";
return 0; }
Functions to manipulate strings:
The c-string 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:
1. String length: returns the length of a string, not including the null character (\0).
strlen (const char* string );
2. String Concatenation: appends source (src) string at the end of destination
(dest) string.
o 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.
o Appending the whole content of the source
strcat ( destination , source );
o Appending part of the source
strncat (char* destination , const char* source, int size );
Where size is the number of characters to be appended
3. String Copy: Overwrites the content of the dest string by the src string.
o 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.
o Copy the whole content of the source
strcpy (char* dest , const char* src );
o Appending part of the source
strncpy (char* dest , const char* src, int size );
Where size is the number characters to be copied
4. String Compare: compares the two string string1 and string2.
o 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.
o Copy the whole content of the source
strcmp (const char* string1 , const char* string2 );
o 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
String object:
In C++, you can also create a string object for holding strings.
Unlike using char arrays, a string object has no fixed length, and can be extended as per
your requirement.
Declaration:
string stringName; // e.g. string str1;
Initialization:
string str1 = “Hello”;
Example: #include<iostream.h>
int main( ){
string str;
cout<<”enter the string”;
getline(cin,str);
cout<<”you entered: “<<str<<endl;
return 0;
}
5.8. Multidimensional Arrays
Multidimensional arrays can be described as arrays of arrays. For example, a bi-
dimensional array can be imagined as a bi-dimensional table of a uniform concrete data
type.
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. Just consider the amount of memory that an array with many indices may
need. For example:
char century [100][365][24][60][60];
Multidimensional arrays are nothing else than an abstraction, since we can simply obtain
the same results with a simple array by putting a factor between its indices:
int matrix [3][5]; is equivalent to
int matrix [15]; (3 * 5 = 15)
Copying string
A library function strcpy or strncpy is used to copy string without using for
loop. Assign strings by using the string copy function strcpy.
Syntax: strcpy(destination, source);
strcpy copies characters from the location specified by source to the location
specified by destination.
It stops copying characters after it copies the terminating null character.
Example:
#include <iostream.h>
#include <string.h>
void main(){
charasu[20] = "Computer Scince";
cout<< me <<endl;
strcpy(asu, "Information Science");
cout<<asu<<endl ;
return; // The return value is the value of the destination parameter.
}
There is also another function strncpy, is like strcpy, except that it copies only a
specified number of characters.
Syntax: strncpy(destination, source, int n);
It may not copy the terminating null character.
Example
#include <iostream.h>
#include <string.h>
int main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout<< one <<endl;
strncpy(one, str2, 2);
cout<< one <<endl;
strcpy(one, str2);
cout<< one <<endl;
return 0;
}
Concatenating string
The strcat() or strncat are used for concatenating strings.
The function strcat concatenates (appends) one string to the end of another string.
Syntax: strcat(destination, source);
The function strncat is like strcat except that it copies only a specified number of
characters.
Syntax : strncat(destination, source, int n);
It may not copy the terminating null character.
Example:
#include <iostream.h>
#include <string.h>
int main() {
char str1[30];
strcpy(str1, "abc");
cout<< str1 <<endl;
strcat(str1, "def");
cout<< str1 <<endl;
char str2[] = "xyz";
strcat(str1, str2);
cout<< str1 <<endl;
str1[4] = '\0';
cout<< str1 <<endl;
return 0;
}
Example:
#include <iostream.h>
#include <string.h>
int main() {
char str1[30];
strcpy(str1, "abc");
cout<< str1 <<endl;
strncat(str1, "def", 2);
str1[5] = '\0';
cout<< str1 <<endl;
char str2[] = "xyz";
strcat(str1, str2);
cout<< str1 <<endl;
str1[4] = '\0';
cout<< str1 <<endl;
return 0;
}
Comparing strings
Strings can be compared using strcmp or strncmp functions.
The function strcmp compares two strings.
Syntax: strcmp(str1, str2); //Compares str1 with str2
Example:
#include <iostream.h>
#include <string.h>
int main()
{
cout<< strcmp("abc", "def") <<endl; //compares abc with def
cout<< strcmp("abc", "ABC") <<endl; //compares abc with ABC
return 0;
}
The function strncmp is like strcmp except that it compares only a specified number of
characters.
strncmp(str1, str2, int n);
strncmp does not compare characters after a terminating null character has been found in
one of the strings.
Example:
#include <iostream.h>
#include <string.h>
void main()
{
cout<<strncmp("abc", "def", 2) <<endl;
cout<<strncmp("abc", "abcdef", 5) <<endl;
}