Posted By:
2 Jul, 2013 6:44 am PDT

Arrays in C++

What are arrays? How to implement arrays? How to access elements in an array?
Attachment:None


An array is a series of elements of same data type stored in contiguous memory location that can be individually accessed by adding an index to a unique identifier.

 

Syntax of array declaration is:

datatype identifier[size];

 

Eg:

 int a[5];

 

In memory, array elements are generally numbered from 0 to size-1.

 0

 1

 2

 3

 4

To understand arrays more clearly, let us take an example. A student writes 5 subjects in his school exams and marks are awarded for each subject. If we take the marks to be in ‘int’ data type, then we have to define five variables m1, m2, m3, m4 and m5. These variables can lead to many confusions while writing functions, to avoid these we can store all the five values in a single array i.e mark[5]. This can be easily accessed and hence functions can be written easily.

 

When declaring a regular array of local scope, if we do not specify otherwise, its elements will not be initialized to any default value. The elements of global arrays, on the other hand, are automatically initialized with the default array i.e., 0.

In both cases, global or local, while declaring we have the option of initializing the array elements. This is done by writing all the values inside {}.

Eg:

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

 

The value of an array element can be accessed using its index. For the above example if we say a[0] then 1 will be printed. The code snippet for accessing the array elements is

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

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

   cout<<a[i];

 

Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud