Sunday, May 26, 2019

C language : Array


Array :     An array is a collection of similar type of data element. It can store only those elements which are of same datatype .
   for eg.             int n[10];

Characteristic of an array:

1. This is homogeneous collection of data elements.

2. Sometimes it is called sub-scripted variable (Index/dimension).

3. When we are assigning array, its type and dimension must be declared.

4. Arrays always stores the elements in contiguous memory location.

5. Whatever, size of the array by default may be it starts to store the element from the zero (0) location location will be one less than the  size of the array.

Declaration of an array:
Every variable must be declared before it is used. The same concept is true in case of array variable also. The array must be declared before its use. Declaring an array means specifying three things:
1. Data type- What kind of value it can store.
  for eg. int, char, float , double.
2. Name to identify the array.
3. Size- The maximum number of values that the array can hold.

Syntax of array:- datatype name[size];
                             eg. int a[10];

Accessing elements of the array:
For accessing an individual elements of array, the array subscript must be used.
 For eg.
 To access the fourth element of the array, we must write arr[3]; . The subscript/ index must be an integral value or an expression that evaluates to an integral value . To access all the elements of the array , we must use a loop. There is no single statement that can do the work i.e., we can access all the elements of the array by varying the value of the subscript into the array. But note that the value of the subscript must be an integral for an expression that evaluates to an integral value. To process all elements of the array we will use a loop as shown:
int i,a[10];
printf (" enter the element");
for(i=0;i<=9;i++)
scanf ("%d",&a[i]);

Calculating the address of array element
An array store all its data element in contiguous memory location.So storing just the base address, i.e, the address of the first element in the array is sufficient. The  address of other data element can simply be calculated using the base address. The formula for doing this calculation is:
Address of data element, A[K]=BA(A)+W(K-lower_bound)
Here A is the array, K is the index of the element for which we have to calculate the address, BA is the base address of the array A, w is the word size of one element in memory ( for example, size of int is 2) and lower bound is the index of the first element in the array.
for eg.
Q.  calculate the address of marks [4] if base address = 1000 given an array int marks[] = {99,67,52,92,71,63}
A.                       99            67            52               92           71          63
       marks        [0]           [1]           [2]            [3]           [4]          [5]
                        1000        1002        1004       1006        1008      1010
we know that storing an integer value we require 2 bytes therefore here,word size is 2 bytes.
marks[4] =1000+2(4-0)
                 = 1000+2*4
                 =1000+8
                 =1008

Storing values in array:
When we declare and define an array, we are just allocating space for the element; no values are stored in the array. To store values in the array there are three ways-
First to initialize the array element; second to input value for every individual element; third to assign values to the element.

Initialization of array:
Elements of the array can also be initialized at the time of declaration as in the case of every other variable.When an array is initialized we need to provide a value for every element in the array. Array are initialized by writing,

data_type array_name[size] = {list of values };
The values are written with curly braces and every values is separated by a comma.
for eg.          int marks[5] = {90,43,65,66,85};

 While initializing the array at the time of declaration, the programmer may omit to mention the size of the array.
 for eg.    int marks[ ] = {56,47,77,92,18};
The above statement is absolutely true, Here the compiler will allocate space for all initialized elements.
If the number of values provided is less than the number of element in the array, then  an unassigned elements are filled with zeros.

for eg.      int marks[5] = {1,2,3,4,5};

                  1      2        3         4           5
                 [0]    [1]     [2]     [3]         [4]

                 int marks[5] = {1,2};
                
                 1       2         0        0          0
                 [0]    [1]     [2]      [3]       [4]

                 int marks[ ] = {1,2,3,4,5};
             
                  1         2       3         4         5
                 [0]       [1]    [2]      [3]       [4]
             
                 int marks[5] = {0};

                 0       0          0           0        0
                 [0]    [1]        [2]       [3]      [4]

If we have more initializers than the declared size of the array, then a compile time error will be generated.
 for eg.   The following statement will result in error:
                    int marks[3] = {1,2,3,4,5};

Calculating the length of array:
Length of an array is given by the number of elements stored in it. The general formula to calculate the length of the array is -
Length = upper bound- lower bound + 1
where upper bound is the index of the last element and lower bound is the index of the first element in the array. Usually lower bound is zero but this is not a compulsion as we can have an array whose index start from non-zero value.

for eg.    int A[2] = {0,1};
           Here, lower bound = 0 and upper bound  = 1
           By formula, it's length is UB -LB +1
                                                 = 0+1+1=> 2
                   Therefore, length is 2


  ONE DIMENSIONAL ARRAY FOR INTER FUNCTION COMMUNICATION


PASSING INDIVIDUAL ELEMENTS:    The individual elements of an array can be passed to a function either by passing their address or their data values.

 PASSING DATA VALUES:      The individual elements can be passed in the same manner as we  pass variables of any other data type condition is just that the data type of the element must match the type of the function parameter.
for eg.             main()
                        {
                           int arr[5] = {1,2,3,4,5};
                               func(arr[3]);
                           }
                          void func(int num)
                         {
                         printf("%d",num);
                       }

In the above example only one element of the array is passed to the calling function. This is done by using the index expression.
So arr[3] ; actually evaluates to single integer value . The called function hardly bothers weather a normal integer variable is passed to it or an array value is passed.

PASSING ADDRESS:  Like a ordinary variable we can pass the address of an individual element by preceding the address operator (&) to the element index reference. Therefore to pass the address of the fourth element of the array to the called function we will write &arr[3].
However, in the called function, the value of the array element must be accessed using the indirection operator (*).          
for eg             main()
                             int arr[3] = {0,1,2};
                          func(&arr[2]);
}
                           void func(int *num)
{
                             printf("%d",num);
}

PASSING THE ENTIRE ARRAY:     The array name refers to the first byte of the array in the memory. The address of the rest of the element in the array can be calculated using the array name      and the index value of the element Therefore, when we need to pass an entire array to a function we can simply pass the name of the array.
for eg.                               main ()
                                    {
                                      int arr[5] = {1,2,3,4,5};
                                         func(arr);
                                      }
                                        void func(int arr[5])
                                   {
                                             int i;
                                             for(i=0;i<=4;i++)
                                      printf("\n   %d",arr[i]);
                                         }

TWO DIMENSIONAL ARRAY: One dimensional array is organized linearly and only in one direction but at times, we need to store data in the form of matrics or tables.
Two dimensional array specified using two subscript or index one subscript denotes row and another subscripts denotes column .
                                    
DECLARATION OF A TWO DIMENSIONAL ARRAYS
Similar to one dimensional array, two dimensional array must be declared before being used. The declaration statement tells the compiler the name of the array, the data type of each element in the array and the size of each dimension. A two dimensional array is declared as:
data_type  array_name [row_size][column];
Therefore, a two dimensional array mXn array is an array that contain mXn data elements and each element is accessed using two subscript i and j where i is less than or equal to m and j is less than or equal to n.
For example.
If you want to store the marks obtained by 3 student in five different subjects then we can declare two dimensional array as-
int marks[3][5];



INITIALIZATION OF TWO DIMENSIONAL ARRAY
Two dimensional array is initialized in the same way as one dimensional array
for eg. 
   int marks[2][3] ={90,87,76,34,72,66};
The initialization of a two dimensional array is done row by row.The above statement can also be written as as-
      int marks[2][3] = {{90,87,76},{34,72,66}};
The given two dimensional array has a 2 row and 3 columns. Here the element in the first row are initialized first and then the elements of a second row are initialized.
Therefore,
   marks [0][0] = 90                   marks [0][1] = 87             marks [0][2] = 76
   marks [ 1][0] = 34                   marks [1][1] = 72            marks [1][2] = 66

In the case of one dimensional array,if the size of the array is completely initialized ,we may omit the size of the array.Same concept can be applied to a two dimensional array except that only the size of the first dimensional  can be omitted. Therefore, the declaration statement given below is valid
for eg.  int marks[ ][3]={{90,87,76},{34,72,66}};

ACCESSING THE ELEMENT
The element in a multidimensional array are stored in contiguous memory allocation. While accessing the elements, remember that the last subscript varies  most rapidly where the first varies least rapidly.
   In case of one dimensional array be used, we used a single for loop to vary the index i in every pass so that all the elements could be scanned. Similarly, since a two-dimensional array contain two subscript, we will use two for loop to scan the element.

TWO DIMENSIONAL ARRAY FOR INTER FUNCTION COMMUNICATION



There are three ways of passing parts of the two-dimensional array to the function.
First we can pass individual element of the array as in case of one dimensional array.
Second we can pass a single row of the two dimensional array. This is equivalent to passing the entire one dimensional array to a function.
Third we can pass the entire two dimensional to the function.

PASSING A ROW
A row of two dimensional array can be passed by indexing the array name with row number. When we send a single row of the two-dimensional array, then the called function receives a one-dimensional array.
For example
main()
{
int arr[2][3]= {{1,2,3},{4,5,6}};
func(arr[1]);
}
void func(int arr[ ])
{
int i;
for (i=0;i<5;i++)
printf("\n %d",arr[i]*10);
}

PASSING AND ENTIRE 2D ARRAY
To pass a 2D array to a function, we use the array name as actual parameter. However, the parameter in the called function must indicate that the array has two dimensions.

MULTIDIMENSIONAL ARRAY
Multidimensional arrays in simple terms is an array of arrays. Like we have one index in One dimension, two indices in two dimension, in the same way we have n number of indices in a n dimensional array.
      Multidimensional array contains as many indices as needed and the requirement of the memory increases with the number of indices used. However, practically, we will hardly used more than three indices in any program.
For example    int arr[2][2][2];


1 comment:

Function

FUNCTION C enables programmer to break up a program into segments commonly known as functions, each of which can be written more or...