C++ Arrays

C++ has two kinds of data types:

a)intrinsic data types (or) primitive data types and

b)complex data types.

Intrinsic data types are basic or fundamental data types implemented directly by C++.They contain the data or values directly.For example, the char data type stores character value and the int data type stores an integer value.Complex data types store more than one value or more than one data.An array is a complex data type.

What is an Array?

The best definition of an array is as follows. An array is:

  • a user defined data type

  • which can hold multiple values

  • of the same data type in one variable

  • in contagious memory locations

  • and where each element can be accessed by an index from 0 to n-1 where n is the size of the array.

Other important features of an array are:

  • The first item in the array is  element 0.

  • The size of the array is the total number of elements  that it can contain.

  • Arrays can be of one dimension or multi-dimensional.

Creating an Array

The general syntax to declare an array of size n of a particular data type is :

<data type> <arrayname>[n] ;

For example an integer array of size 14 is defined as:

int arr[14];

It can contain elements from 0 to 13.Please remember to use the square braces [ ].You can also initialise an array with data in the following manner.

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

  • int arrayname[10] = {1, 2, 3}; 

    • In this case, only 3 values are assigned to the first 3 elements of the array.The remaining values will be set to 0 by default for int arrays.

Array values can be accessed in the following manner.

int myarray[ ] = {10,11,12,13,14,15,16,17}; 
int mynumber = myarray[4];

Now mynumber variable will contain the value at index 4 which is 14. Remember that in an array the index starts from 0 and ends at n-1 where n is the size of the  array. An important point to note here is that if you try to access an index outside this range, then C++ will not throw any error.It will return some random garbage value.

An array is a pointer to a memory location.The first element of the array is the starting memory address for the entire array.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: