0% found this document useful (0 votes)
11 views7 pages

Chapter Two Programming II

Chapter Two discusses arrays in C++, explaining their definition as collections of identical data objects stored in consecutive memory locations. It covers properties, declaration, initialization, accessing elements, and passing arrays as parameters, emphasizing the importance of array indices and the zero-based indexing system. Additionally, it introduces multidimensional arrays and their equivalence to single-dimensional arrays in terms of memory representation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
11 views7 pages

Chapter Two Programming II

Chapter Two discusses arrays in C++, explaining their definition as collections of identical data objects stored in consecutive memory locations. It covers properties, declaration, initialization, accessing elements, and passing arrays as parameters, emphasizing the importance of array indices and the zero-based indexing system. Additionally, it introduces multidimensional arrays and their equivalence to single-dimensional arrays in terms of memory representation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 7

Chapter Two

Arrays

Motivation
Suppose that we want a program that can read in a list of numbers and sort that
list, or find the largest value in that list. To be concrete about it, suppose we
have 15 numbers to read in from a file and sort into ascending order. We could
declare 15 variables to store the numbers, but then how could we use a loop to
compare the variables to each other? The answer is that we cannot.
An array is conceptually a linear collection of elements, indexed by subscripts, all
of the same type.

2. 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.

2.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, and your program
will crash or have unexpected results, depending on the compiler.
􀀹Array can only hold values of one type
Things to remember about arrays:
 The starting index of an array is 0, not 1.
 The last index is one less than the size of the array.
 If the array has size elements, the range is 0...size-1.
 Arrays contain data of a single type.
 An array is a sequence of consecutive elements in memory and the start of
the array is the address of its first element.
 Because the starting address of the array in memory is the address of its first
element, and all elements are the same size and type, the compiler can
calculate the locations of the remaining elements

2.2. Array declaration a (one-Dimensional )


􀀹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
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:

DataTypename 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.

2.3. 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:

􀀹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

2
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.
Rules
 If the array size is given in brackets, then the initialized list must have at most
that many values in it. If it has fewer, the rest of the array is initialized to 0's.
 If the size is not given in brackets, then the size is equal to the number of
elements in the initializer list.
 If there is no initializer list, none of the array elements are initialized. They are
not set to 0.

2.4. 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:

3
􀀹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:

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; void main ()
{ for ( n=0 ; n<5 ; n++ )
{
result += day[n];
}
cout << result;
getch();
}
How to insert and print array elements?

4
􀀹The following example shows to to insert each array element and display each
array elements

int mark[5] ={10, 10, 8, 17, 9};


//change the 4th element to 9
Mark[3]=9;
//take input from the user and store the value at the third position
cin>>makr[2];
//take input from the user and insert on the i th position
cin>>mark[i-1];
//print first element of the array
cout<<mark[0];
//print the ith element of the array
cout<<mark[i-1]

2.5. Arrays as parameters


􀀹At some moment we may need to pass an array to a function as a parameter. In
C++ it is not possible to pass by value a complete block of memory as a
parameter, even if it is ordered as an array, to a function, but it is allowed to
pass its address, which has almost the same practical effect and is a much faster
and more efficient operation.
􀀹In order to admit arrays as parameters the only thing that we must do when
declaring the function is to specify in the argument the base type for the array
that it contains, an identifier and a pair of void brackets [] . For example, the
following function:
void procedure (int arg[])
􀀹admits a parameter of type "Array of int " called arg . In order to pass to this
function an array declared as:
int myarray [40];
􀀹it would be enough with a call like this:
procedure (myarray);
Here you have a complete example:
// arrays as parameters #include <iostream.h>
#include <conio.h>
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n";
}
void mult(int arg[], int length)
{ for (int n=0; n<length; n++)
arg[n]=2*arg[n];
}
void main ()
{ int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);

5
printarray (secondarray,5);
mult(firstarray,3);
cout<<”first array after being doubled is\n”;
printarray (firstarray,3);
getch()
}
􀀹As you can see, the first argument (int arg[] ) admits any array of type int ,
whatever its length is, for that reason we have included a second parameter that
informs the function the length of each array that we pass to it as the first parameter
so that the for loop that prints out the array can have the information about the size
we are interested about. The function mult doubles the value of each element and
the firstarray is passed to it. After that the display function is called. The output is
modified showing that arrays are passed by reference.
􀀹To pass an array by value, pass each element to the function
2.6 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.

􀀹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]

(remember that array indices always begin by 0 )


􀀹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?
6
􀀹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
int matrix [HEIGHT][WIDTH];
int n,m;
int main ()
{
for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++)
{
matrix [n][m]=(n+1)*(m+1);
}
return 0;
}
􀀹None of the programs above produce any output on the screen, but both assign
values to the memory block called matrix in the following way:

􀀹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

You might also like