Array
Array
Array
Syntax:
data_type array_name[array_ size];
For example:
float mark[5];
Few Keypoints:
• Arrays have 0 as the first index not 1. In this example,
mark[0].
• If the size of an array is n, to access the last element, (n-1)
index is used. In this example, mark[4].
• Suppose the starting address of mark[0] is 2120d. Then, the
next address, mark[1], will be 2124d, address of mark[2] will
be 2128d and so on. Its because the size of a float is 4 bytes.
How to Initialize an array?
Its possible to initialize an array during declaration.
For example:
int mark[5] ={9,4,6,3,5};
Another method of initialize array during declaration
int mark[ ] ={9,4,6,3,5};
Here,
mark[0] is equal to 9
mark[1] is equal to 4
mark[2] is equal to 6
mark[3] is equal to 3
mark[4] is equal to 5
Important thing to remember when working with
C arrays:
Suppose you declared an array of 10 elements. Letssay,
int testArray[10];
1. One-dimensional arrays.
2. Two-dimensional arrays.
3. Multidimensional arrays.
One-dimensional Array:
Example:
float height[50];
int groupt[10];
char name[10];
The type specifies the type of the element that will be
contained in the array, such as int, float, or char and the size
indicates the maximum number of elements that can be stored
inside the array.
Now as we declare a array
int number[5];
Then the computer reserves five storage locations as
the size o the array is 5 as show below.
number[0] number[0] 35
number[1] number[1] 20
number[2] number[2] 40
number[3] number[3] 57
number[4] number[4] 19
Initialization of one dimensional array:
At compile time
At run time
Compile Time Initialization:
The general form of initialization of array is:
type array-name[size] ={list of values};
The values in the list are separated by commas.
For example:
int number[3] ={0,5,4};
for(i=0;i<10;i++)
{
scanf(“%d”, &x[i]);
}
In the run time initialization of the arrays looping
statements are almost compulsory.
Initializing Two-DimensionalArrays:
Multidimensional arrays may be initialized by
specifying bracketed values for each row.
Following is an array with 3 rows and each row
has 4 columns.
int a[3][4] = {
{0,1,2,3},
{4,5,6,7},
{8,9,10,11}
};
The nested braces, which indicate the intended
row, are optional. The following initialization is equivalent
to the previous example
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional ArrayElements:
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
Multi-Dimensional Arrays:
Element of Amatrix
a[1][1]:1
a[1][2]:4
a[2][1]:6
a[2][2]:3
Element of Bmatrix
b[1][1]:1
b[1][2]:7
b[2][1]:3
b[2][2]:9
Addition of a matrix is
2 11
9 12