Chapter 2 Array and String
Chapter 2 Array and String
Chapter Two
2. Arrays, Strings and Structure
2.1. What is An Array?
A collection of identical data objects, which are stored in consecutive memory locations under a
common heading or a variable name. In other words, an array is a group or a table of values referred
to by the same name. The individual values in array are called elements. Array elements are also
variables.
Set of values of the same type, which have a single name followed by an index. In C++, square
brackets appear around the index right after the name
A block of memory representing a collection of many simple data variables stored in a separate array
element, and the computer stores all the elements of an array consecutively in memory.
Page 1 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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:
Page 2 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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.
int arr [] = {16, 2, 77, 40, 12071};
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.
Page 3 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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.
Following the previous examples where day had 5 elements and each element is of type int, the name,
which we can use to refer to each element, is the following one:
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.
In C++ it is perfectly valid to exceed the valid range of indices for an Array, which can cause certain
detectable problems, since they do not cause compilation errors but they can cause unexpected results
or serious errors during execution. The reason why this is allowed will be seen ahead when we begin
to use pointers.
At this point it is important to be able to clearly distinguish between the two uses the square brackets
[ ] have for arrays.
One is to set the size of arrays during declaration
The other is to specify indices for a specific array element when accessing the elements of the
array
Page 4 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
We must take care of not confusing these two possible uses of brackets [ ] with arrays:
Eg: 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;
day[0]=a;
day[a]=5;
b=day[a+2];
day [day[a]] = day [2] + 5;
day [day[a]] = day[2] + 5;
Eg: Arrays example ,display the sum of the numbers in the array
#include<iostream.h>
int day [ ] = {16, 2, 77, 40, 12071};
int n, result=0;
int main () {
for ( n=0 ; n<5 ; n++ ) {
result += day[n];
}
cout << result;
}
2.2. Strings of Characters
Page 5 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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:
H e l l 0 \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.
Page 6 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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.
Page 7 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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.
Page 8 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
{
char szMyName [20];
strcpy (szMyName,"Abebe");
cout << szMyName;
return 0;
}
Look how we have needed to include <string.h> header in order to be able to use function strcpy.
Although we can always write a simple function like the following setstring with the same operating
than cstring's strcpy :
// setting value to string
#include <iostream.h>
#include<conio.h>
void namecopy(char dest[], char source[]){
int c = 0;
while(source[c] != ‘\0’) {
dest[c] = source[c];
c++;}
dest[c] = ‘\0’;
cout<< “\n your name after copying : ”<<dest;
}
int main(){
char name[10],dest[10];
cout<< “\n enter your name : ”;
cin>>name;
namecopy(dest,name);
getch();
}
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.
When cin is used with strings of characters it is usually used with its getline method, that can be called
following this prototype:
cin.getline ( char buffer [], int length , char delimiter = ' \n');
Page 9 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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' ).
The following example repeats whatever you type on your keyboard. It is quite simple but serves as
example on how you can use cin.getline with strings:
// cin with strings
#include <iostream.h>
#include<conio.h>
int main ()
{
char mybuffer [100];
cout << "What's your name? ";
cin.getline (mybuffer,100);
cout << "Hello " << mybuffer << ".\n";
cout << "Which is your favourite team? ";
cin.getline (mybuffer,100);
cout << "I like " << mybuffer << " too.\n";
getch();
return 0;
}
Notice how in both calls to cin.getline we used the same string identifier ( mybuffer ). What the
program does in the second call is simply step on the previous content of buffer by the new one that is
introduced.
If you remember the section about communication through console, you will remember that we used
the extraction operator ( >> ) to receive data directly from the standard input. This method can also be
used instead of cin.getline with strings of characters. For example, in our program, when we requested
an input from the user we could have written:
cin >> mybuffer;
this would work, but this method has the following limitations that cin.getline has not:
It can only receive single words (no complete sentences) since this method uses as delimiter any
occurrence of a blank character, including spaces, tabulators, newlines and carriage returns.
Page 10 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
It is not allowed to specify a size for the buffer. What makes your program unstable in case that
the user input is longer than the array that will host it.
For these reasons it is recommendable that whenever you require strings of characters coming from
cin you use cin.getline instead of cin >> .
Page 11 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
Page 12 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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
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.
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 compaired
Both string compare functions returns three different values:
o Returns 0 is the strings are equal
o Returns negative value if the first is less than the second string
o Returns positive value if the first is greater than the second string
Page 13 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
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. Just consider the
amount of memory that an array with many indices may need. For example:
char century [100][365][24][60][60];
Assigns a char for each second contained in a century, that is more than 3 billion chars ! What would
consume about 3000 megabytes of RAM memory if we could declare it?
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)
With the only difference that the compiler remembers for us the depth of each imaginary dimension.
Serve as example these two pieces of code, with exactly the same result, one using bi-dimensional
arrays and the other using only simple arrays:
// multidimensional array
#include <iostream.h>
#define WIDTH 5
#define HEIGHT 3
Page 14 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
We have used defined constants ( #define ) to simplify possible future modifications of the program,
for example, in case that we decided to enlarge the array to a height of 4 instead of 3 it would be
enough by changing the line:
#define HEIGHT 3
by the following code
#define HEIGHT 4
Page 15 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
Worksheet No
1. Define strlen function (i.e write the function body of strlen)
2. Define the strcmp function and the strncmp function
3. Define strcpy function and the strncpy function
4. Define strcat function and the strncat function
5. Write a program to store the ages of six of your friends in a single array. Store each of the six ages using the assignment
operator. print the ages on the screen
6. Write a C++ program that accepts 10 integers from the user and finally displays the smallest value and the largest value.
7. Write a program that accepts ten different integers from the user and display these numbers after sorting them in increasing
order.
8. Write a program to store six of your friend’s ages in a single array. Assign the ages in a random order. print the ages, from
low to high, on-screen
9. Modify the program on Q8 to print the ages in descending order.
10. Write a C++ program that calculates the letter grades of 20 students. The program should accept the mid result and the final
result from the students. Use the appropriate validity control mechanism to prevent wrong inputs.
11. Write a C++ program that has two functions toBinary and toDecimal. The program should display a menu prompting the user
to enter his choice. If the user selects toBinary, then the function should accept a number in base ten and displays the
equivalent binary representation. The reverse should be done if the user selects toDecimal.
12. Develop a C++ program that accepts a word from the user and then checks whether the word is palindrome or not. (NB a
word is palindrome if it is readable from left to right as well as right to left).
13. Write a C++ program that accepts a word from the user and then displays the word after reversing it.
14. Develop a C++ program that accepts the name of a person and then counts how many vowels the person’s name have.
15. Modify the question in Q14 in such a way that it should replace vowel characters with * in the person name.
16. Write a program in C++ which read a three digit number and generate all the possible permutation of numbers using the
above digits. For example n = 123 then the permutations are – 123, 213, 312, 132, 231, 321
17. Write a program which read a set of lines until you enter #.
18. Write a program which read two matrixes and then print a matrix which is addition of these two matrixes.
19. Write a program which reads two matrix and multiply them if possible
20. Write a program which reads a 3 x 2 matrix and then calculates the sum of each row and store that in a one dimension array.
Page 16 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
2.4. Structure
What is a Structure?
Structure is a collection of variables under a single name. Variables can be of any type: int, float, char
etc. The main difference between structure and array is that arrays are collections of the same data type
and structure is a collection of variables under a single name.
In the above example, it is seen that variables of different types such as int and float are grouped in a
single structure name Customer. Arrays behave in the same way, declaring structures does not mean
Page 17 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
that memory is allocated. Structure declaration gives a skeleton or template for the structure. After
declaring the structure, the next step is to define a structure variable.
What happens when this is defined? When structure is defined, it allocates or reserves space in
memory. The memory space allocated will be cumulative of all defined structure members. In the
above example, there are 3 structure members: custnum, name and phonenum. Of these, two are of type
in and one is of type char. If integer space allocated by a system is 2 bytes and char one bytes the above
would allocate 2bytes for custnum, 2 bytes for phonenum and 1byte for name.
Page 18 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
Page 19 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
Page 20 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
struct Company
{
int employees;
int registers;
double sales;
}store[1000];
In one quick declaration, this code creates 1,000 store structures with the definition of the Company
structure, each one containing three members.
NB. Be sure that your computer does not run out of memory when you create a large number of
structures. Arrays of structures quickly consume valuable information.
You can also define the array of structures after the declaration of the structure.
struct Company
{
int employees;
int registers;
double sales;
}; // no structure variables defined yet
#include<iostream.h>
void main()
{
struct Company store[1000]; //the variable store is array of the structure Company
…
}
struct student
{
int id;
float mark;
char name[15];
}stud[2];
int main()
{
for(int i=0;i<=1;i++)
{
cout<<"Enter the id, name and mark of student"<<i+1<<endl;
cin>>stud[i].id>>stud[i].name>>stud[i].mark;
}
for(int i=0;i<=1;i++)
{
cout<<"Id of Student "<<i+1<<"="<<stud[i].id<<endl;
cout<<"Name of Student "<<i+1<<"="<<stud[i].name<<endl;
cout<<"Mark of student "<<i+1<<"="<<stud[i].mark<<endl;
}
}
Page 22 of 24 KIOT
Fundamentals of Programming- II Chapter Two: Arrays ,Strings and Structure
char title[50];
int year;
};
int main ()
{
char buffer[50];
Book b1;
Book * pb1;
Pb1 = &b1;
cout << "Enter title: ";
cin.getline (pb1->title,50);
cout << "Enter year: ";
cin.getline (buffer,50);
pb1->year = atoi (buffer);
cout << "\nYou have entered:\n";
cout << pb1->title;
cout << " (" << pb1->year << ")\n";
return 0;
}
The previous code includes an important introduction: operator. This is a reference operator that is
used exclusively with pointers to structures and pointers to classes. It allows us not to have to use
parenthesis on each reference to a structure member. In the example we used:
Pb1->title
that could be translated to:
(*pb1).title
both expressions pb1->title and (*pb1).title are valid and mean that we are evaluating the element title
of the structure pointed by pb1. You must distinguish it clearly from:
Book favourite_Book;
} S1, S2;
student * pstud = &S1;
Therefore, after the previous declaration we could use the following expressions:
S1.name
S2.favourite_Book.title
S1.favourite_Book.year
pstud->favourite_Book.year
(where, by the way, the last two expressions are equivalent).
Page 24 of 24 KIOT