Вы находитесь на странице: 1из 32

Arrays

2
Introduction to Arrays
An array is a list of elements of the same type stored
contiguously.
Any array has a name (that is a constant pointer to the
first element)

The type of the elements is the type of the array

Types:
One-dimensional (vectors in C)
Multi-dimensional
3
One-dimensional arrays (vectors - C)
Declaration:
type array_name[dim];

type is a data type (predefined or user defined)
array_name is an identifier
[ ] is a delimitation
dim is a positive integer constant expression that specifies the
number of elements
4
To access an element we use the index operator [ ],
specifying the array_name and the position in the array
by an index:
array_name [index]

index is a positive integer expression

First element has the index 0 and the last element,
index (dim-1)
5
Considering the number and the type of the array
elements the compiler will determine the allocation
dimension by:
dim_memory = sizeof(type) * dim

Example:
int tab[100];

first element: tab[0]
last element (100): tab[99]
the i+1 element: tab[i]
allocation sizeof(int)*100 = 2(4)00
6
After allocation the compiler will not verify the index
range:
tab[200] will not be an error at the execution, but error as data
processing

7
Remarks:
1. The specified dimension must be an integer
constant:
const int SIZE = 10;
int score[SIZE/2];
2. It is not allowed as dimension an expression with
variables:
int size;
cout << "Enter number of students: ";
cin >> size;
int score[size]; // incorect !
3. An array declaration may appear anywhere where
are declared variables of the same type:
int i, score[5], x, y, z;
8
Declaration:
type array_name [dim
1
][dim
2
]...[dim
N
];

To refere an element:
array_name [index
1
][index
2
]...[index
N
];

If n=2 we have a matrix
Example: float tab[10][5];

In C/C++ we have no restrictions concerning the number of
dimensions for a multi-dimensional array.
Multidimensional arrays
9
A multidimensional array is a one-dimensional array
that as elements has arrays

Example:
int tab[2][3];

is an array with 2 elements each element is a one-dim array of 3 int
numbers.
Logical structure:



10
Memory structure:

The access to an element:
array_name[index
1
][index
2
]...[index
N
]
0 tab[0][0]
1 tab[0][1]
2 tab[0][2]
3 tab[1][0]

4 tab[1][1]

5 tab[1][2]

11
4. Array elements
An array element may appear anywhere where may
appear a simple variable of the same type:
assign:
tab[i] = 23;
KB input:
cin >> tab[i];
scanf(%d, &tab[i]);
output:
cout << tab[i];
printf(%d, tab[i]);
calculus:
sum += tab[i];
function call:
Celsius = F_to_C(tab[0]);
12
5. Declaration init arrays
If are not explicit initialized the local arrays elements are
undefined

The init process may be realized at the declaration by
using a list of values separated by comma, between
curly braces.
13
One dimensional arrays:
type array_name[dim] = {ec
0
, ..., ec
N-1
};

If dim is not specified the number of constant expressions will
give the array dimension
If dim is specified, the elements that are not explicit init will be 0
For character strings the curly braces may be omitted

Examples:
int tab[ ] = {1,3,5,7,9,11};
float tab[5] = {0,1,2};
char tab[ ] = "abcd";//4 elements and \0
14
Multidimensional arrays:
type name[n][m]= {
{ec
11
,...,ec
1m
},
{ec
21
,...,ec
2m
},...,
{ec
n1
,...,ec
nm
}
};
where: n, m, ec
ij
, are constant expressions (indexes from 0 to n-1,
respective from 0 to m-1)

Inside, curly braces may be omitted, but if we consider, will
specify the row init process
Example:
int tab[3][2] = { {10,11},
{12,13},
{14,15} };
15
6. Array elements processing
It is preferred the anterior recursive instruction for()
because we know the number of elements that are
sequential processed:
The cycle variable is used as array index
Other variable or a symbolic constant that represents the array
dimension is used in the associate condition
16
One-dimensional arrays:

for (int i=0; i<arraySize; i++)
cin >> temperature[i];

for (int i=0; i<arraySize; i++)
cout << temperature[i] << endl;

int sum=0;
for (int i=0; i<arraySize; i++)
sum += temperature[i];

Remark: All (last two) operations could be realised in the
same loop to increase the performance

17
Bidimensional arrays:

for (int row = 0; row < 10; row++)
for (int col = 0; col < 10; col++)
{
cout << "Enter a value for Arr[ " << row << , col " << col << ]: ";
cin >> numArr[row][col];
}


for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 10; col++)
cout << numArr[row][col];
cout << endl;
}
18
Example bidimensional array: main diagonal sum

int arr[10][10];

int sum = 0;
for (int row = 0; row < 10; row++)
for (int col = 0; col < 10; col++)
if (row == col)
sum += arr[row][col];

cout << Suma elementelor de pe diagonala principala este: "
<< sum << endl;

19
7. Arrays as function parameters
An array may be transferred as parameter to a function.
In this case:
Formal parameter is declared as an array with same type and
dimension with the array used as argument
Formal parameter is declared as an array where the first (left)
dimension may be ignored
Formal parameter is declared as a pointer to the array type
In any case as argument we use the array address
At one-dimensional arrays we may consider as
parameter an array with no dimension.
Usual in this case we have other parameter that
represents the array dimension, that is an int variable

20
// prototype
void read_data(int score[ ], int size);

// definition
void read_data(int score[ ], int size)
{
for (int i=0; i<size; i++)
cin >> score[i];
}

// call
int tab1[120], tab2[110];
read_data(tab1,120);
read_data(tab2,110);
21
In the calling process the first parameter is named array
parameter (first element address)

Such a calling mechanism is an address calling that will
specify everything about the array, without the
dimension.

Using this parameter and the index element it is possible
to calculate the address of any element from the array

In this mode any operation concerning the array realized
inside the function will be visible outside
22
We may use a const modifier to the array so that we are
not able to modify the array elements:
void displayArray ( const int arr [ ], int MAXSIZE );


For multidimensional arrays, the first dimension (left)
may be omitted concerning the allocation mechanism of
an array in C:
void display(char p[ ][100], int size)
23
const int SIZE=5;

double calcAvg (double numbers[ ], int max);
void printArray(double[ ], int);

void main( )
{
double temps[SIZE];
int index;
double avg;
cout << "Enter " << SIZE << " temperatures\n";
for (index=0; index< SIZE; index++)
cin >> temps[index];
avg = calcAvg(temps, SIZE);
cout << "The average is: " << avg << endl; printArray(temps, SIZE);
}
24
double calcAvg (double numbers[ ], int count)
{
double sum=0;
for (int i=0; i<count; i++)
sum += numbers[i];
return sum/count;
}

void printArray(double numbers[ ], int count)
{
for (int i=0; i<count; i++)
cout << numbers[i] << endl;
}


25
7. Searching elements in an array
It is a very frequent operation
Usual we search the position of an element with a
certain value
If array is not sorted we use a linear search algorithm:
A sequential elements crossing is realized with the comparison
with the searched value
If a value is found, the index element is returned, otherwise
value -1 is returned
The algorithm will find the first occurrence of the value
26
int linear_search(int arr[ ], int n, int val)
{
int pos;
for(pos = 0; pos < n; pos++)
if (arr[pos] == val)
return pos;
return -1;
}

For small arrays the algorithms is Ok
27
Binary search:
We verify if the middle element is the searched value
If yes, we return the position
If no, we search to left or right side
We continue the process till we find an element or the
interval is null
28
// we supose that the array is increasing sorted
int binarySearch(int arr[ ], int size, int target)
{
int middlePosition, middleValue;
int low = 0, high = size - 1;

while (low <= high)
{
middlePosition = (low + high) / 2;
middleValue = arr[middlePosition];
if (target == middleValue)
return middlePosition;
else if (target < middleValue)
high = middlePosition - 1;
else
low = middlePosition + 1;
}
return -1;
}
29
8. Insert an element in the array
For unsorted arrays, to insert a new element we must
consider:
Must exist space in the array;
The new element will determine a usual right shifting of some
array elements

For sorted arrays, we first must find the position where to
insert the new value so that the array will remain sorted

30
Unsorted arrays

void insert_at(int arr[ ], int n, int idx, int val)
{
if (idx == -1)
arr[n] = val; // adaugare
else
{
// deplasare dreapta
for(int i = n; i > idx; i)
arr[i] = arr[i-1];
// inserare valoare noua
arr[idx] = val;
}
}

31
Sorted arrays

void insertElement ( int arr [ ], int &size, int newElement )
{
int insertPosition, k;

// cautare pozitie inserare
insertPosition = -1;
do
insertPosition++;
while ( newElement > arr[insertPosition] && insertPosition != size - 1 );

if ( newElement <= arr[insertPosition] ) {
// deplasare dreapta
for ( k = size - 1; k >= insertPosition; k-- )
arr[k+1] = arr[k];
// inserare
arr[insertPosition] = newElement;
}
else
arr[size] = newElement; // adaugare
size++;//se va vedea si in exterior
}
32
9. Delete arrays element
As to insert, to delete will impose usual left shifting of
some array elements
We suppose that we know where we delete the element,
otherwise a searching algorithm will be used

void deleteElement ( int arr [ ], int &size, int position )
//size is reference to have the modified value outside
{
int k;

if ( position >= size )
cout << "Eroare ! Index incorect. ";
else
{
// deplasare stanga
for ( k = position; k < size - 1; k++ )
arr[k] = arr[k+1];
--size;
}
}

Вам также может понравиться