• Register

An array in programming is a collection of items or data of the same data type. For example an array of names would be a string array in which the items would be like “John”, “James”, “Kate” etc. Arrays are useful for holding many homogenous data values in memory to be used. An array is simply collection of values of the same data type. Arrays have a fixed size which is defined the programmer. While they can be made to act as dynamic but technically arrays always have a fixed size.

 

Arrays are created and accessed as indexes. The first index is 0 not 1, so that means if you create an array of 10 numbers the indexes would be (0, 1, 2, …., 9). The last index would be 9 not 10.

 

How to declare an array: –

<data_type> <array_name> [ <array_size> ] ;

 

Example: –

   int numbers [10] ;

 

To initialize an array: -

<data_type> <array_name> [ <array_size> ] = { <val_1>, <val_2>, …, <last_val> } ;

 

Example:  -

   int numbers [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ;

 

The size of an array indicates how many elements or items are in the array.

 

Finding the size of an array is kind of an old problem but one still a lot of people especially new programmers ask. There are a few ways of finding the size of an array :

 

1) Using sizeof operator: -

    For this the programmer would need to use the following syntax:

            sizeof ( <array_name> ) / sizeof ( <array_name> [0] )

 

    Example: -

            int numbers [] = {1, 2, 3, 4, 5, 6, 7, 8, 9} ;             

      cout<< “Size of Array = “<< sizeof (numbers) / sizeof  (numbers [0] ) ;

 

2) Using pointers: -

     For this way use the following syntax:

            *( &<array_name> + 1 ) - <array_name>

 

     Example: -

             int numbers [] = {1, 2, 3, 4, 5, 6, 7, 8, 9} ;

      cout<< “Size of Array = “<< *(&numbers + 1) – numbers ;

 

3) Using for - loop: -

    This is another way but it is longer to code and is isn’t the most efficient way of calculating the size of an array and it      also might take longer to compute so the 2 above methods are much better but this is another way of finding out 

    array size. In this we use a for-loop and iterate until we find an empty or null position in the array. 

    We store the  answer in a variable.

 

    The C++ coding below is how to find size of an array using a for-loop:

 

      int numbers [] = {1, 2, 3, 4, 5, 6, 7, 8, 9} ;

      int count = 0 ;

      for(int i = 0; i <= 10000; i++)

      {

         if ( numbers[i]  == NULL )

         {

            count = i ;

            break ;

         }

     }

    cout << "Size of Array: "<< count;

100 points
2