Arrays Part1

                                                                  ARRAYS
                                                       (SUB SCRIPTS)

Definition:
An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar type of elements as in the data type must be the same for all elements. They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers etc. Given below is the picturesque representation of an array.

Why do we need arrays?
We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.
Types of Arrays:

Arrays can of following types:

1. One dimensional (1-D) arrays or Linear arrays
2. Multi dimensional arrays
(a) Two dimensional (2-D) arrays or Matrix arrays
(b) Three dimensional arrays

1. One dimensional (1-D) arrays or Linear arrays:

In it each element is represented by a single subscript. The elements are stored in consecutive memory locations. E.g. A [1], A [2], ….., A [N].

2. Multi dimensional arrays:
(a) Two dimensional (2-D) arrays or Matrix arrays:

In it each element is represented by two subscripts. Thus a two dimensional m x n array A has m rows and n columns and contains m*n elements. It is also called matrix array because in it the elements form a matrix. E.g. A [2] [3] has 2 rows and 3 columns and 2*3 = 6 elements.

(b) Three dimensional arrays:
In it each element is represented by three subscripts. Thus a three dimensional m x n x l array A contains m*n*l elements. E.g. A [2] [3] [2] has 2*3*2 = 12 elements.


1. One dimensional (1-D) arrays or Linear arrays:


conceptual-representation-of-one-dimensional-array

Syntax: datatype array_name[size];

int a[6];

Here by default location starts from 0

By default each location occupies 2 bytes

Each location has garbage value

Array length is 6

Array memory size is 12 bytes(6*2=12bytes)

Array Address 111(base address)


datatype: It denotes the type of the elements in the array.

array_name: Name of the array. It must be a valid identifier.

size: Number of elements an array can hold.

here are some example of array declarations:

num is an array of type int, which can only store 100 elements of type int.
temp is an array of type float, which can only store 20 elements of type float.
ch is an array of type char, which can only store 50 elements of type char.

Note: When an array is declared it contains garbage values.

The individual elements in the array:

1
2
3
num[0], num[1], num[2], ....., num[99]
temp[0], temp[1], temp[2], ....., temp[19]
ch[0], ch[1], ch[2], ....., ch[49]


We can also use variables and symbolic constants to specify the size of the array.

1
2
3
4
5
6
7
8
9
10
#define SIZE 10
 
int main()
{
    int size = 10;
 
    int my_arr1[SIZE];
    int my_arr2[size];
    // ...
}

Accessing elements of an  1 D array

The elements of an array can be accessed by specifying array name followed by subscript or index inside square brackets (i.e []). Array subscript or index starts at 0. If the size of an array is 10 then the first element is at index 0, while the last element is at index 9. The first valid subscript (i.e 0) is known as the lower bound, while last valid subscript is known as the upper bound.

then elements of this array are;

First element – my_arr[0]
Second element – my_arr[1]
Third element – my_arr[2]
Fourth element – my_arr[3]
Fifth element – my_arr[4]

Array subscript or index can be any expression that yields an integer value. For example:

In the array my_arr, the last element is at my_arr[4], What if you try to access elements beyond the last valid index of the array?

Sure indexes 5, 10 and -1 are not valid but C compiler will not show any error message instead some garbage value will be printed. The C language doesn’t check bounds of the array. It is the responsibility of the programmer to check array bounds whenever required.

Processing 1-D arrays

The following program uses for loop to take input and print elements of a 1-D array.

Expected Output:

1
2
3
4
5
6
7
8
9
Enter a[0]: 11
Enter a[1]: 22
Enter a[2]: 34
Enter a[3]: 4
Enter a[4]: 34
 
Printing elements of the array:
 
11 22 34 4 34

Initializing 1 D Array:

When an array is declared inside a function the elements of the array have garbage value. If an array is global or static, then its elements are automatically initialized to 0. We can explicitly initialize elements of an array at the time of declaration using the following syntax:

Syntax: datatype array_name[size] = { val1, val2, val3, ..... valN };

datatype is the type of elements of an array.

array_name is the variable name, which must be any valid identifier.

size is the size of the array.

val1, val2 … are the constants known as initializers. Each value is separated by a comma(,) and then there is a semi-colon (;) after the closing curly brace (}).

Here is are some examples:

While initializing 1-D array it is optional to specify the size of the array, so you can also write the above statements as:

If the number of initializers is less than the specified size then the remaining elements of the array are assigned a value of 0.

here the size of temp array is 5 but there are only two initializers. After this initialization the elements of the array are as follows:

temp[0] is 12.3
temp[1] is 4.1
temp[2] is 0
temp[3] is 0
temp[4] is 0


Advantages of Arrays:


  • Arrays represent multiple data items of the same type using a single name.
  • In arrays, the elements can be accessed randomly by using the index number.
  • Arrays allocate memory in contiguous memory locations for all its elements. Hence there is no chance of extra memory being allocated in case of arrays. This avoids memory overflow or shortage of memory in arrays.

advantages and disadvantages of arrays


  • Using arrays, other data structures like linked lists, stacks, queues, trees, graphs etc can be implemented.
  • Two-dimensional arrays are used to represent matrices.

Disadvantages of Arrays:


  • The number of elements to be stored in an array should be known in advance.
  • An array is a static structure (which means the array is of fixed size). Once declared the size of the array cannot be modified. The memory which is allocated to it cannot be increased or decreased.
  • Insertion and deletion are quite difficult in an array as the elements are stored in consecutive memory locations and the shifting operation is costly.
  • Allocating more memory than the requirement leads to wastage of memory space and less allocation of memory also leads to a problem.
Draw Backs of arrays:
1)It has wastage of memory
2)It Accept only similar data type elements

Applications of Arrays:

  • Arrays are used to implement mathematical vectors and matrices, as well as other kinds of rectangular tables. Many databases, small and large, consist of one-dimensional arrays whose elements are records.
  • Arrays are used to implement other data structures, such as lists, heaps, hash tables, deques, queues and stacks.
  • One or more large arrays are sometimes used to emulate in-program dynamic memory allocation, particularly memory pool allocation. Historically, this has sometimes been the only way to allocate "dynamic memory" portably.
  • Arrays can be used to determine partial or complete control flow in programs, as a compact alternative to (otherwise repetitive) multiple “if” statements. They are known in this context as control tables and are used in conjunction with a purpose built interpreter whose control flow is altered according to values contained in the array. The array may contain subroutine pointers(or relative subroutine numbers that can be acted upon by SWITCH statements) that direct the path of the execution.


Array declaration in C++/C:


Comments