3. What are Arrays?
An array is a series of elements of the same
data type placed in contiguous memory
locations that can be individually referenced by
adding an index to a unique identifier.
That means that, for example, we can store 5
values of type int in an array without having to
declare 5 different variables, each one with a
different identifier. Instead of that, using an
array we can store 5 different values of the
same type, int for example, with a unique
identifier.
6. Declaration & Initialization
int billy [5]; //declaration
int billy [5] = { 16, 2, 77, 40, 12071 };
OR int billy [] = { 16, 2, 77, 40, 12071 };
8. Important
The most important thing to remember about
array allocation is that the elements of the
array are indexed starting at 0, not 1. If the
number of cells in an array is N, then the
indexes run from 0 to N-1.
9. Accessing the elements of an
array.
We can access the value of any of its
elements individually as if it was a normal
variable, thus being able to both read and
modify its value.
billy[2] = 75;
a = billy[2];
b = billy [a+2];
A= billy[2] + 5;
10. int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
11. sizeof
Imagine you declare an array as follows:
int number[] = {18, 42, 25, 12, 34, 15, 63, 72,
92, 26, 26, 12, 127, 4762, 823, 236, 84, 5};
Instead of counting the number of members of
this array you can use sizeof as follows:
int var= sizeof(number)/sizeof(int);
12. Things you cannot do
int array[10];
cout << array << endl;
int array[10];
cin >> array;
17. Example
Copy one string into another
char str1[15],str2[15];
int I;
cout<<“ENTER STRING”;
cin>>str1;
for(i=0;str[i]!=„0‟;i++)
str2[i]=str1[i];
str2[i]=„0‟;
18. Next class
Think over the logic of
Insert an element into an array
Delete an element from the array
Merge two arrays