20. What are arrays.

An Array is a collection of similar elements strode in adjacent memory locations. An ordinary variable is capable of storing only one value at a time. However, there are situations in which we would want to store more than one value at a time in a single variable. Suppose we wish to store the percentage marks obtained by 100 students in memory. In such a case we have two options to store these marks in memory:
1.   Construct 100 variables to store percentage marks obtained by 100 different students; i.e. each variable containing one student’s.
2.   Construct one variable (called a subscripted variable) capable of storing or holding all the hundred marks.
Obviously, the second alternative is better.

To fix our ideas, let us note down a few facts about arrays:
1.   An array is a collection of similar elements. It is also known as a subscripted variable.
2.   Before using an array its type and size must be declared. For example:
int arr[30];
float a[60];
char ch[25];

3.   The first element in the array is numbered 0, so the last element is 1 less than the size of the array.
4.   However big an array may be, its elements are always stored in contiguous memory locations.
5.   If we so desire an array can be initialized at the same place where it is declared. For example,
int num[6]={2,3,23,32,4,45,5}
int n[] ={2,3,23,32,4,45,5}
float press[]={12.3,45.6,25.8,-11.3}

6.   If the array is initialized where it is define, mentioning the dimension of array is optional as in second example above.
7.   If the array elements are not given any specific values, they are supposed to contain garbage values.
8.   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.  This will lead to unpredictable results, to say the least, and there will be no error message to warn you that you are going beyond the array size. In some cases the computer may just hang. Thus, the following program may turn out to be suicidal:

/*Program*/
Main()
{
int num[40];
for (i=0;i<=100;i++)
num[i]=i;
}

So do remember that, ensuring that we do not reach beyond the array size is entirely the programmer’s botheration and not the compiler’s.
Taken from "nderstanding Pointers IN C"

2 comments:

  1. Plz write about two dimantional array.

    ReplyDelete
  2. Thanx for you comment. Ok, we will post a artical about two dimantional array.

    ReplyDelete

free counters