Wednesday 8 February 2012

Arrays

Introduction to Array

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
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.
This is the memory storage of an array of 5 same type of data.

where each panel represents an element of the array, These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.

Classification to Array:

Arrays are classified as
Single dimensional array
Multi dimensional array: these can be two dimensional ,three dimensional etc…

Declaration of multi dimentional Array


Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C….

              Data_type   arrayname[size of array];


Where
Arrayname -> name of the array
Size of array-> number of elements of datatype.and size must be an integer constant specified with in a pair of square brackets.
Example :
Int   list[10];
Char  name[20];
The first declaration creates an array of name list with 10 integer constants.the second declaration creates  name as an array of 20 characters.

NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a  constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed.


Total memory size of an array

Total size= size *(size of(data_type));
Where ,
Size -> number of elements in one dimensional array.
Size of() -> is an unary operator to find the size in bytes.
Data_type-> basic data type.
For example: total size of one dimensional array of 10 integer is 20 bytes. Because, the size of an integer data is 2 bytes.

Initialization of Array


When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros.
In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example:

Data_type arrayname[size]= {element 1,element2,element3…………………………..elementn};

Where,
Element1……………element-> are the initial values enclosed in acurly braces.and these must be                                               separated by commas.
Example: int evennum[4]={2,4,6,8};
This declaration initializes the first four elements of an array evennumby 4 even integers  as shown



Accessing values of Array

In any point of a program in which an array is visible, 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. The format is as simple as:

Name[index];


Example: to assign a value to second location of the array  evennum, we give the following statement:
Evennum[1];
This statement will give the value 4 from the array evennum.
In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems, since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The reason why this is allowed will be seen further ahead when we begin to use pointers.
At this point it is important to be able to clearly distinguish between the two uses that brackets
[ ] have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets [ ] with arrays.
Example:
int  list[10];     declaration of array.
List[9]= 44;       giving value 44 in the array at location 10th.

Programs based on single dimentional Array

The program accepts n integers and stores them in an array called num. it also print them


#include<stdio.h>
main()
{
Int n,I,num[20];
Printf(“enter the size of array”);
Scanf(“%d”,&n);
Printf(“enter the elements one by one”);
For(i=0;i<n;i++);
{
Scanf(“%d”, &num[i]);
}
Printf(“array is \n”);
For(i=0;i<n;i++)
{
Printf(“num[%d]=%d\n”,I,num[i]);
}
}



Output:
Enter the size of array
3
Enter  the elements one by one
1 2
2 3
4 5
Array is
Num[0]=12
Num[1]=23
Num[2]=45

Multi Dimentional Array


MULTIDIMENSIONAL ARRAYS
If the number of subscripts is more than 1, then such arrays are called multidimensional arrays. Thus we can say two-dimensional array(2-D),three-dimensional(3-D) array and so on.
The dimensionality is understood from the pair of square brackets placed after the array name.
Example:
  • Array1[]    : one-dimensional array
  • Array2[][]    : two-dimensional array
  • Array3[][][] : three- dimensional array.
The programmer will fill in each pair of brackets, the number of elements
To be processed.

Two dimentional Array

it is an ordered table of homogenious elements. It is generally, referred to as matrix of some rows and some columns. It is also called as two subscripted variable.
Declaration of two dimensional  array:
The syntax of declaration of  two  dimensional  array  is as  follows:
Datatype  aaray_name[row][column];
Where ,
Rows->  number of elements to be processed in subscript1.
Column-> number off elements to be processed  in subscript2.
Example:
Int marks[5][3];
Float matrix[3][3];
The first example tells that marks is atwo-dimensional  array  of 5 rows and 3 columns. Rows may represent  students and  columns may represent tests. Pictorial representation of first example is:

The subscript value ranges from 0 to(size-1) in c. therefore the subscript value for students varies from 0 to 4. Similarly the  value for test varies from 0 to 2. And subscript are shown in parenthesis. Thus we have,


Similarly for all the values can be processed. this indicates that for each row (student number) element, column element(tests) are rapidly processed. This type of arrangement  is known as row major order(ie row is prominent).and the column major order is one where for each column, the row elements are rapidly processed.

Initialization of two-dimensional array


Like initialization of one- dimensional elements, two-dimensional array elements can also be initialized at the time of declaration . the syntax for two-dimensional array inititialisation is as follows:
Datatype array_name[size1][size2]={e1,e2,e3…………………..en};
Where,
Datatype-> basic datype
Arrayname->name of two-dimensional array
e1,e2,………en->initial values to be assigned to n elements of array.
Consider the following declaration
Int matrix[3][3]={1,2,3,4,5,6,7,8,9)
Then ,
First nine element s of the matrix will be,
Matrix[0][0]=1;
Matrix[0][1]=2;
.
.
Matrix[2][2]=9;
If the number of elements to be assigned is less then the total number of elements that two-dimensional array contained, then all the remaining elements are assigned zero.
Example:
Float xy[2][2]={1.0,2.0,3.0};
Here, xy is a two dimensional array of 2X2 elements of type float. But , only the first three elements are initialized. The fourth element is then automatically set to zero.
Xy[0][0]=1.0
Xy[0][1]=2.0
Xy[1][0]=3.0
Xy[1][1]=0.0
You can also initialize values to the individual elements of a two dimensional array from the given set of values.
Example:
Int num[2][2]={{1,2},{3,4});
Here the inner set {1,2} is taken for assigning values 1 and 2, respectively to the first row element of an array  num. thus,
Num[0][0]=1
Num[0][1]=2
Similarly the other set {3,4} is taken for assigning its values 3 and 4, respectively, to the second row of an array num. thus,
Num[1][0]=3
Num[1][1]=4.

Remember the following points while dealing with the initialization of the two dimensional array elements.
  • The number of sets of initial values must be equal to the number of rows in the array.
  • One to one mapping is preserved i.e. the set of initial values is assigned to the first row elements and the second set of initial values is assigned to the second row elements and so on.
  • If the number of initial values in each initialisg set is less than the number of corresponding row elements of that row are automatically assigned to zero.
  • If the number of initial values in each initialisg set exceeds the number of the corresponding row elements then there will be compilation error.

Program based on two dimentional Array

#include<stdio.h>
main()
{
Int n,I,j,row,col;
Int mat[10][10];
Printf(“enter the order of matrix\n”);
Scanf(“%d%d”,&row,&col);
Printf(“enter the elements of matrix\n”);
For(i=0;  i<row;  i++)
{
For(j=0; j<col;j++)
{
Scanf(“%d”,&mat[i][j]);
}
}
Printf(“matrix is\n”);
For(i=0; i<row; i++)
{
For(j=0; j<col; j++)
{
Printf(“%d”,mat[i][j]);
}
Print(“\n”)
}
}

Output:
Enter the order of matrix
3 3
Enter the elements of matrix
1
2
3
4
5
6
7
8
9
Matrix is
1 2 3
4 5 6
 7 8 9

Arrays as perimeters

At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation. 
In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For example, the following function.
void procedure (int arg[])
accepts 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 to write a call like this:
procedure (myarray);
In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:
base_type[][depth][depth]
for example, a function with a multidimensional array as argument could be: 
void procedure (int myarray[][3][4])

Notice that the first brackets [] are left empty while the following ones specify sizes for their respective dimensions. This is necessary in order for the compiler to be able to determine the depth of each additional dimension.
Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors for novice programmers. I recommend the reading of the chapter about Pointers for a better understanding on how arrays operate.



No comments:

Post a Comment