In this C++ Tutorial you will learn about Concepts of Arrays in C++, what is an array, how to access an array element, declaration of array and how to access array elements.
What is an array?
An array is a group of elements of the same type that are placed in contiguous memory locations.How to access an array element?
You can access an element of an array by adding an index to a unique identifier.
For example
Suppose Exforsys is an array that has 4 integer values in it that is of int data type, then Exforsys is internally represented as:
Exforsys Data Type :Declaration of Array:
Just like variables, we have to declare arrays before using them. The general syntax for declaring an array is
data_type array_name[number_of_elements];
In the above example the declaration of array Exforsys would be written as:
int Exforsys[4];
One of the key points when declaring arrays is the number of elements defined in the array argument must be a constant value. The size of the array must be known before its execution. This relates to the concept of dynamic memory allocation in C++ which will be covered later in the tutorial.
After declaration the next step is the initialization of array values.
Initialization of array:
If a programmer wants to initialize an array elements it can be done by specifying the values enclosed within braces { }.
For example, using the array Exforsys, if a programmer wants to initialize integer values 10, 20, 30, 40 respectively to each of the array positions it can be written.
int Exforsys[4] = {10,20,30,40};
So the above array would take values as below
Exforsys Data Type : intOne interesting fact is that the size of the array element can also be left blank, in which case the array takes the size of the array as the number of elements initialized within { }.
For example if the array takes the form as
int Exforsys = {10,20,30,40,50};
Then the size of the array Exforsys is 5 which is the number of elements initialized within { }.
Now the next step is to know how to access the array elements.
How to Access Array Elements:
Just like variable sit is possible to access any element of the array for reading or modifying.
The general format for accessing arrays:
array_name[index]
For example in the above example of array initialized with
int Exforsys[4] = {10,20,30,40};
When a programmer wants to access the 30 this can be written:
Exforsys[2]
Note that the array starts with index 0 and hence to access the third element which is 30, the index has to be 2.
Let us see the whole concept with a example:
#include <iostream>
using namespace std;
int Exforsys[ ] = { 10,20,30,40,50};
int i, outp=0;
void main()
{
for(i=0;i<5;i++)
{
outp=outp + Exforsys[i];
}
cout << outp;
}
The output of the above program is:
This section covers the concept of array and single dimensional array.
In the next chapter of this tutorial, multidimensional arrays will be covered.