400+ Editable Festival Posters + Free Bonuses

PART 1 : Lesson 9 : Array

<< Previous Lesson          Back To Main Index          Next Lesson >>


Array Declaration
Accessing Elements of an Array 
Entering Data into an Array
Reading Data from an Array
Array Initialization
Array Elements in Memory


Call By Value
Call By Reference












 An array is a sequenced collection of related data items that share a common name.
                                                         OR
An array is a set of elements of the same data type represented by a single variable name. Each individual array element can be referred to by specifying the array name, followed by a subscript enclosed in square brackets. Arrays may be 1-Dimensional or multi-dimensional array, depending upon the subscript enclosed in square brackets.

Suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such a case we have two options to store these marks in memory:-

Ø Construct 100 variables to store percentage marks obtained by 100 different students. i.e. each variable containing one student’s marks.
Ø Construct one variable (called array or subscripted variable) capable of storing or holding all the hundred values.
The second alternative is better. A simple reason for this is it would be much easier to handle one variable than handling 100 different variables.
Ø An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, or salaries of 300 employees, or ages of 50 employees. Each member in the group is referred by its position in the group.

Example:-       Per = {48, 88, 34, 23, 96}
                                                Per [0], Per [1], Per [2], Per [3], Per [4]

Ø An array is a collection of similar elements. These similar elements could be all ints or all floats or all chars etc. The array of characters is called a string where as an array of ints or floats are called simply an array. Remember that all elements of any given array must be of the same type. i.e. we cannot have an array of 10 numbers, of which 5 are ints and 5 are floats.

Example:-       // W.A.P. to find average marks obtained by a class of 30 students in a test.
void main( )
{
            float avg, sum=0;
            int i;
            int marks [30];                                     // Array declaration…           
                                               
            for (i=0; i<=29; i++)
            {
                        printf ("\n Enter marks: ");
                        scanf ("%d", &marks [i]);        // Store data in Array….
}

for (i=0; i<=29; i++)
{
                        sum= sum + marks [i];          // Read data from Array..
}


            avg=sum/30;
            printf ("%f", avg);
            getch( );
}


§  Array Declaration
§  Accessing elements of an Array
§  Entering Data into an Array
§  Reading Data from an Array

1)                  Array Declaration:-

We declare other variables so an array needs to be declared also so that the complier will know what kind of an array and how large an array we want. In programming we can do this with this statement:
§  int marks [30];

Ø  Here, int specifies the type of the variable, just as it does with ordinary variables.
Ø  The word marks specifies the name of the variables.
Ø  The [30] however is new. The number 30 tells how many elements of the type int will be in an array. This number is often called the ‘dimension’ of array.
Ø  The bracket [ ] tells the compiler that we are dealing an array.

2)                  Accessing Elements of an Array:-

Individual elements in the array can be referred. The number in the bracket is size of following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks [2] is not the second element of the array but the third. We are using the variable i as a subscript to refer to various elements of the array. These variables can show different values and can refer to the different elements in the array in turn.

3)                  Entering Data into an Array:-

We can enter data into array according to previous program as follow:
            for (i=0; i<=29; i++)
            {
                        printf ("\nEnter marks: ");
                        scanf ("%d", &marks [i]);
}

The for loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. The first time through the loop, i has a value 0, so the scanf ( ) statement will cause the value typed to be stored in the array element marks [0], the first element of the array. This process will be repeated until i becomes 29. This is last time through the loop, which is a good thing, because there is no array element like marks [30].



In the scanf ( ) statement, we have used the “addressof” operator (&) on the element marks [i] of the array.

4)                  Reading Data from an Array:-

for (i=0; i<=29; i++)
{
            sum=sum + marks [i];
}
avg= sum/30;
printf ("\nAverage marks = %f", avg);

Ø    An array is a collection of similar elements.
Ø    The first element in the array is numbered 0, so the last element is 1 less than the size of the array.
Ø      An array is also known as a subscripted variable.
Ø      Before using an array its type and dimension must be declared.
Ø  However big an array its elements are always stored in contiguous memory locations.

More on Arrays:-

Array is a very popular data type among c programmers. This is because of the convenience with which arrays lend themselves to programming. The features which make arrays so convenient to program would be discussed below, along with the possible pitfalls in using them.

Array Initialization:-
 We manage to store values in them during execution.

Example:-

§  int num [6]= {2, 4, 12, 5, 45, 5}
§  int n [ ] = {2, 4, 12, 5, 45, 3}
§  float press [ ] = { 12.3, 33.3, -32.4, -11.2}

Important Points to be Followed:-

Ø  Till the array elements are not given any specific values, they are supposed to contain garbage values.
Ø  If the array is initialized where it is declared mentioning the dimension of the array is optional as in the 2nd example above.

Array Elements in Memory:-


§  int arr [8];

Ø  16 bytes get immediately reserved in memory. 16, because each of the 8 integer would be 2 byte long. And since the array is not being initialized, all eight values present in it would be garbage values. This happens so because the storage class

of this array is assumed to be auto. If the storage class is declared to be static then all the array elements would have a default initial value as zero.



In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; probably on top of other data, or on the program itself.
void main( )
{
            int  num [5], i;
            for (i=0; i<=10; i++)
            {
                        num [i] =i;
            }
}
                       
            In this case, Output will be the following result:

Ø  This will lead to unpredictable results.
Ø  No error message to warn you that you are going beyond the array size.
Ø  In some case the computer may just hang.

To see that we don’t reach beyond the array size is entirely the programmer’s botheration and not the compiler’s.



Array elements can be passed to a function by calling the function by value or by reference.
Ø  In the call by value we pass values of array elements to the function.
Ø  In the call by reference we pass address of array elements to the function.
Call By Value:-
                             
Example:-
void display(int m);
void main( )
{
            int i;
            int marks [ ]= {55, 66, 77, 88, 99, 11, 9};
            for (i=0; i<=6; i++)
            {
                        display (marks [i]);
}
}



void display (int m)
{
                        printf ("%d ", m);
}                                  

Output:-          55  66  77  88  99  11  9

Here, we are passing an individual array element at a time to the function display ( ) and getting it printed in the function display ( ). At a time only one element is being passed, this element is collected in an ordinary integer variable m, in the function display ( ).

Call By Reference: -

Example:-
void disp (int *m);
void main( )
{
            int i;
            int marks []= {55, 66, 77, 88, 99, 11, 9};
            for (i=0; i<=6; i++)
            {
                        disp (&marks [i]);
}
}
void disp (int  *m)
{
                        printf ("%d  ", *m);
}
                       
                        Output:-          55  66  77  88  99  11  9

Here, we are passing addresses of individual array elements to the function disp ( ) function. Hence, the variable in which this address is collected (m) is declared as pointer variables and since m contains the address of array element, to print the array element we are using the “Value at Address” operator (*).



Example:-
                                   
void main ( )
{
            int i=3, *x;
            float j=1.5, *y;
            char k=’c’, *z;

           
            printf ("\nValue of i=%d", i);
            printf ("\nValue of j=%f", j);
            printf ("\nValue of k=%c", k);

            x=&i;
y=&j;
            z=&k;

            printf ("\nOriginal address in x=%u", x);
            printf ("\nOriginal address in y=%u", y);
            printf ("\nOriginal address in z=%u", z);
           
            x++;
            y++;
            z++;
           
            printf ("\nNew address in x=%u", x);
            printf ("\nNew address in y=%u", y);
            printf ("\nNew address in z=%u", z);

}



Ø  Suppose i, j and k are stored in memory at addresses 1002, 2004 and 5006.

Output:-          Value of i=3
Value of j=1.5
Value of k=c
Original address in x=1002
Original address in y=2004
Original address in z=5006
New address in x=1004
New address in y=2008
New address in z=5007

Ø  int takes 2-byte storage in memory.
Ø  float takes 4-byte storage in memory.
Ø  char takes 1-byte storage in memory.
   


We can also pass an entire array to a function rather than its individual elements.
Example:-
void display (int *j, int n);
void main( )
{
            int num []= {24,34, 44, 55, 66, 77};
            display (&num [0], 6);
}
void display (int *j, int n)
{
            int i;
            for (i=0; i<=n-1; i++)
            {
                        printf ("%d  ", *j);
                        j++;
}
}
                       
                        Output:-          24  34  44  55  66  77



If you have storage of array elements in memory and arithmetic of pointers then we can declare the above array in C like this,
                                                int num [] = {24, 34, 44, 55, 66, 77} ;


Ø  *num we would be able to refer to the 0th element of the array, that is 24.
Ø  One can easily see that *num and *(num+0) both refer to 24.
Ø  Similarly, by saying *(num+1) we can refer the first element of the array, that is 34.

Examples:- 


Prove the Points:-

Example:-

void main( )
{
            int num [] = {24, 34, 44, 55, 66, 77};
            int i;
 for (i=0; i<=5; i++)
            {
                        printf ("\nAddress= %u", &num [i]);
                        printf ("\tElement=%d", num[i]);
                        printf("\t%d", *num[i+1]);
                        printf ("\t %d %d ", *(num+i), i[num]);
}
}

Ø    We use the
§     &num [i]
§     (num [i], *num [i+1])
§     *(num+i), i[num]

Output:-          Address=4001             Element= 24    24        24        24
                                                Address=4003             Element= 34    34        34        34
            Address=4005             Element= 44    44        44        44
            Address=4007             Element= 55    55        55        55
            Address=4009             Element= 66    66        66        66
            Address=4011             Element= 77    77        77        77


It is also possible for arrays to have two or more dimensions. The two dimensional array formats is also called a matrix.      
           
Example:-
void main( )
{
            int stud [4][2];
            int i,j;
            printf ("\nEnter Roll no. and marks : ");
 for (i=0; i<=3; i++)
            {                                                                     
                        scanf ("%d %d", &stud [i][0], &stud [i][1]);
}
   
            for (i=0; i<=3; i++)
            {
                        printf ("\n %d %d", stud [i][0], stud [i][1]);
            }
}

                        Output:-         Enter Roll no. and marks :
                                                1234    56
                                                1400    78
                                                1212    66
                                                1410    89

Ø    Here stud [i] is the row and the stud [0] and stud [1] is the columns.



int stud [4][2]= {
                        {1234, 56},
                        {1212, 66},
                        {1400, 78},
                        {1410, 89}
                        } ;
                                                                                    OR

int stud [4][2]= {1234, 56, 1212, 66, 1400, 78, 1410, 89};

Here it mentions the first dimension for row and second dimension for column. Then the 4 is row and 2 is column.

Ø  int stud [][] = {12, 34, 23, 44, 55, 66};

In this declaration, it does not work probably and not perfectly acceptable.



The arrangement of two dimensional array in memory is shown below:

Array name
S 0][0]
S[0][1]
S[1][0]
S[1][1]
S[2][0]
S[2][1]
S[3][0]
S[3][1]
Data
1234
56
1212
66
1400
78
1410
89
Memory Address
5002
5004
5006
5008
5010
5012
5014
5016

In this,  memory does not contain rows and columns. In memory whether it is  one-dimensional or a two dimensional array, the array elements are stored in one continuous chain.
  
Ø  We can easily refer to the marks obtained by the third student using the subscript notation as shown below:

§  printf ("Marks of third Student=%d", stud [2][1]);



More specifically each row of a two dimensional array can be thought of as a one dimensional array. This is a very important fact if we wish to access array elements of a two dimensional array using pointers.

/* DEMO: 2-D Array is an Array of Arrays */
                                   
void main( )
{
            int s[5][2] = {
                                    {1234, 56}
                                    {1212, 33}
                                    {1434, 80}
                                    {1312, 78}
                        } ;
            int i,j;
            for (i=0; i<=3; i++)
            {
                        printf ("\n Address of %d th 1-D Array= %u", s[i]);
            }
}
           
Output:-          Address of 0th 1-D Array = 5002
                                                Address of 1st 1-D Array = 5006
                                                Address of 2nd 1-D Array = 5010
                                                Address of 3rd 1-D Array = 5014

The compiler knows that s is an integer array. So each element of this array occupies 2 bytes. There are two elements in each row, so each row takes 4 bytes. Thus, each row starts 4 bytes further along than the last one. And since each row is one dimensional array, each of these one dimensional arrays, starts 4 bytes further along than the last one.

Ø  We also refer some elements for declaration.
§  S[2][1]      
§  (s[2]+1)
§  (*(s+2)+1)

Ø  In the three types of declaration, all have same output of these declarations.
  
/* Pointer Notation to Access 2-D Array Elements */
void main( )
{
            int s[5][2] = {
                        {1234, 56},
                        {1212, 33},
                        {1434, 80},
                        {1312, 78}
       };
            int i,j;
            for (i=0; i<=3; i++)
            {
                        printf ("\n");
                        for (j=0; j<=3; j++)
                        {
                                    printf ("%d", *(*(s+i) +j));
            }
}
}
                       
                        Output:-          1234    56
                                                1212    33
                                                1434    80
                                                1312    78

Three Dimensional Array:
                                     
                        Example:-
                                                int arr [3][4][2] = {       {          {2, 4}, 
                                                                                                {7, 8},
                                                                                                {3, 4},
                                                                                                {5, 6}
},
{          {7, 6},
                                                                                                {3, 4),
                                                                                                {5, 3},
                                                                                                {2, 3}
},
{          {8, 9},
                                                                                                {7, 2},
                                                                                                {3, 4},
                                                                                                {5, 1}
}
} ;

A Three Dimensional array can be thought of as an array of arrays of arrays. The outer array has three elements, each of which is a two dimensional array of four one dimensional arrays, each of which contains five integers. In other words, a one dimensional array of two elements is constructed first. Then four such one dimensional array are placed one below the other to give a two dimensional array containing four rows. Then, three such two dimensional arrays are placed one behind the other to yield a three dimensional array containing three 2-Dimensional arrays. In the array declaration note how the commas have been given.

Again remember that the arrangement shown above is only conceptually true. In memory the same array elements are stored linearly as shown in below.


The way there can be an array of ints or an array of floats, similarly there can be an array of pointers. Since a pointer variable always contains an address, an array of pointers would be nothing but a collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses. All rules that apply on an ordinary array, apply on the array of pointers as well.

Example:-

void main( )
{
            int *arr[4];       // array of integer points….
            int i=31, j=5, k=19, L=71, m;
            arr [0] = &i;
arr [1] = &j;
            arr [2] = &k;
                                               
           
            arr [3] = &L;
            for (m=0; m<=3; m++)
            {
                        printf ("%d\t", *(arr[m]));
}
}

                        Output:-          31        5          19        71       


Ø    arr contains addresses of isolated int variables i, j, k and L.

Ø    Arrangement of the Array of pointers in memory:





1 comment:

  1. YUKON GOLD Online Casino | Play £10, Get 30 Free Spins rb88 rb88 카지노 카지노 966Oklahoma Thunder Odds & Betting Odds - Choe Casino

    ReplyDelete

Awesome Gadgets for Students and IT People