Arrays Concept in C++ Language

Ratings:
(4)
Views: 0
Banner-Img
Share this blog:

Arrays in C++

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means that, for example, five values of type int can be declared as an array without having to declare 5 different variables (each with its own identifier). Instead, using an array, the five int values are stored in contiguous memory locations, and all five can be accessed using the same identifier, with the proper index. For example, an array containing 5 integer values of type int called foo could be represented as: Arrays in C++ where each blank panel represents an element of the array. In this case, these are values of type int. These elements are numbered from 0 to 4, being 0 the first and 4 the last; In C++, the first element in an array is always numbered with a zero (not a one), no matter its length. Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:

 type name [elements];

where type is a valid type (such as int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies the length of the array in terms of the number of elements.

Declaration of Arrays

An array declaration is very similar to a variable declaration. First a type is given for the elements of the array, then an identifier for the array and, within square brackets, the number of elements in the array. The number of elements must be an integer.

For example data on the average temperature over the year in Britain for each of the last 100 years could be stored in an array declared as follows:

float annual_temp[100];

This declaration will cause the compiler to allocate space for 100 consecutive float variables in memory. The number of elements in an array must be fixed at compile time. It is best to make the array size a constant and then, if required, the program can be changed to handle a different size of array by changing the value of the constant,

const int NE = 100;
float annual_temp[NE];

then if more records come to light it is easy to amend the program to cope with more values by changing the value of NE. This works because the compiler knows the value of the constant NE at compile time and can allocate an appropriate amount of space for the array. It would not work if an ordinary variable was used for the size in the array declaration since at compile time the compiler would not know a value for it.

Accessing Array Elements

Given the declaration above of a 100 element array the compiler reserves space for 100 consecutive floating point values and accesses these values using an index/subscript that takes values from 0 to 99. The first element in an array in C++ always has the index 0, and if the array has n elements the last element will have the index n-1.

An array element is accessed by writing the identifier of the array followed by the subscript in square brackets. Thus to set the 15th element of the array above to 1.5 the following assignment is used:

annual_temp[14] = 1.5;

Note that since the first element is at index 0, then the ith element is at index i-1. Hence in the above the 15th element has index 14.

An array element can be used anywhere an identifier may be used. Here are some examples assuming the following declarations:

const int NE = 100,

N = 50;

int i, j, count[N];

float annual_temp[NE];

float sum, av1, av2;

A value can be read into an array element directly, using cin

cin >> count[i];

The element can be increased by 5,

count[i] = count[i] + 5;

or, using the shorthand form of the assignment

count[i] += 5;

Initialisation of arrays

An array can be initialised in a similar manner as the initialisation of simple variables in their declaration . In this case the initial values are given as a list enclosed in curly brackets. For example initialising an array to hold the first few prime numbers could be written as follows:

int primes[] = {1, 2, 3, 5, 7, 11, 13};

Note that the array has not been given a size, the compiler will make it large enough to hold the number of elements in the list. In this case primes would be allocated space for seven elements. If the array is given a size then this size must be greater than or equal to the number of elements in the initialisation list. For example:

int primes[10] = {1, 2, 3, 5, 7};

would reserve space for a ten element array but would only initialise the first five elements.

A sample C++ program to store and calculate the sum of 5 numbers entered by the user using arrays.

#include <iostream>
using namespace std; 
int main() 
{    
   int numbers[5], sum = 0;    
   cout << "Enter 5 numbers: ";        
   // Storing 5 number entered by user in an array    
   //  Finding the sum of numbers entered    
   for (int i = 0; i < 5; ++i)     
   {       
       cin >> numbers[i];       
       sum += numbers[i];   
   }      
   cout << "Sum = " << sum << endl;          
   return 0;
}

Output

Enter 5 numbers:

3

4

5

4

2

Sum = 18

Things to remember when working with arrays in C++

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can use the array members from testArray[0] to testArray[9].

If you try to access array elements outside of its bound, let's say testArray[14], the compiler may not show any error. However, this may cause unexpected output (undefined behavior).

 

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox