Chapter Fourarrayprinted

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Chapter Four

Arrays and Strings

In programming, one of the frequently arising problem is to handle similar types of data.
Consider this situation: You have to store marks of more than one student depending upon the
input from user. These types of problem can be handled using C++ programming (almost all
programming language have arrays) using arrays.

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 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.
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, and your program will crash or have unexpected results, depending
on the compiler. Array can only hold values of one type.
Array declaration
Declaring the name and type of an array and setting the number of elements in an array is
called dimensioning the array. The array must be declared before one uses in like other
variables. In the array declaration one must define:
1. The type of the array (i.e. integer, floating point, char etc.)
2. Name of the array,
3. The total number of memory locations to be allocated or the maximum value of each
subscript. i.e. the number of elements in the array.
So the general syntax for the declaration is:

DataType arrayname [array size];

The expression array size, which is the number of elements, must be a constant such as 10 or a
symbolic constant declared before the array declaration, or a constant expression such as
10*sizeof (int), for which the values are known at the time compilation takes place.
Note: array size cannot be a variable whose value is set while the program is running. Thus to
declare an integer with size of 10 having a name of num is: int num [10]; This means: ten
consecutive two byte memory location will be reserved with the name num.
That means, we can store 10 values of type int without having to declare 10 different 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.
Initializing Arrays

When declaring an array of local scope (within a function), if we do not specify the array
variable will not be initialized, so its content is undetermined until we store some values in it.
If we declare a global array (outside any function) its content will be initialized with all its
elements filled with zeros. Thus, if in the global scope we declare:
int day [5];
every element of day will be set initially to 0:
0 1 2 3 4
0 0 0 0 0

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

0 1 2 3 4

16 2 77 40 12071

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.
Accessing and processing array elements
In any point of the program in which the array is visible we can access individually anyone of its
elements for reading or modifying it as if it was a normal variable. To access individual
elements, index or subscript is used. The format is the following:
name [ 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.
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.
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
We must take care of not confusing these two possible uses of brackets [ ] with arrays:

Example 1: C++ Array

#include <iostream>

using namespace std;

int main() {

int n[5]={10,20,30,40,50};
cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]

cout<<"Second number: "<<n[1]<<endl;

cout<<"Third number: "<<n[2]<<endl;

cout<<"Fourth number: "<<n[3]<<endl;

cout<<"Last number: "<<n[4]; // last element of an array is n[SIZE_OF_ARRAY - 1]

return 0;

Example 2: C++ Array

C++ Program to store 5 numbers entered by user in an array and display first and last number
only.

#include <iostream>

using namespace std;

int main() {

int n[5];

cout<<"Enter 5 numbers: ";

/* Storing 5 number entered by user in an array using for loop. */

for (int i = 0; i < 5; i++) {

cin>>n[i];

cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]

cout<<"Last number: "<<n[4]; // last element of an array is n[SIZE_OF_ARRAY - 1]

return 0;

}
C++ Multi-dimensional Arrays

C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:

int threedim[5][10][4];

Two-Dimensional Arrays:

The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional
integer array of size x,y, you would write something as follows:

type arrayName [ x ][ y ];

Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.

A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns. A 2-dimensional array a, which contains three rows and four columns can
be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays:

Multidimensioned arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements:

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:

int val = a[2][3];


Eg1. Example of two -dimensional array
#include <iostream>
using namespace std;
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
// output each array element's value
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;
}

When the above code is compiled and executed, it produces the following result:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.

Eg2. C++ Program to display all elements of an initialized two dimensional array.

#include <iostream>
using namespace std;

int main() {
int test[3][2] = {
{2, -5},
{4, 0},
{9, 1}
};
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 2; ++j) {
cout<< "test["<< i << "][" << ;j << "] = " << test[i][j]<<endl;
}
}
return 0;
}

The output is as follows:


test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1

Eg3:

#include <iostream>
using namespace std;

int main() {
int test[3][2] = {
{2, -5},
{4, 0},
{9, 1}
};
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 2; ++j) {
cout<< "test["<< i << "][" << j << "] = " << test[i][j]<<endl;
}
}
return 0;
}

C++ Strings

C++ provides following two types of string representations:

 The C-style character string.

 The string class type introduced with Standard C++.

The C-Style Character String:

The C-style character string originated within the C language and continues to be supported
within C++. This string is actually a one-dimensional array of characters which is terminated by
a null character '\0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the string
is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as follows:

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++:

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above-mentioned string:

Example1:

#include <iostream>
using namespace std;
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}

Example2: C++ program to display a string entered by user.

#include <iostream>
using namespace std;

int main() {
char str[100];
cout<<"Enter a string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
cout<<"\nEnter another string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
return 0;
}

When the above code is compiled and executed, it produces result something as follows:

Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated strings:

String Functions & their Purpose


1 strcpy(s1, s2): Copies string s2 into string s1.
2 strcat(s1, s2): Concatenates string s2 onto the end of string s1.
3 strlen(s1): Returns the length of string s1.
strcmp(s1, s2): Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
4
s1>s2.

Following example makes use of few of the above-mentioned functions:

#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}

When the above code is compiled and executed, it produces result something as follows:

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

The String Class in C++:

The standard C++ library provides a string class type that supports all the operations mentioned
above, additionally much more functionality. We will study this class in C++ Standard Library
but for now let us check following example:

At this point, you may not understand this example because so far we have not discussed Classes
and Objects. So can have a look and proceed until you have understanding on Object Oriented
Concepts.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
// copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// total lenghth of str3 after concatenation
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}

When the above code is compiled and executed, it produces result something as follows:

str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

You might also like