• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

Arrays Concept in C++ Language

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).

For Indepth knowledge on C++ click on:

Polymorphism in C++

Our course design of tutorials is practical and informative. At TekSlate, we offer resources to help you learn various IT courses. We avail both written material and demo video tutorials. For in-depth knowledge and practical experience explore Online C++ Training.

Summary
Review Date
Reviewed Item
Arrays Concept in C++ Language
Author Rating
4

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on Arrays Concept in C++ Language"

    Leave a Message

    Your email address will not be published. Required fields are marked *

    Site Disclaimer, Copyright © 2016 - All Rights Reserved.

    Support


    Please leave a message and we'll get back to you soon.

    I agree to be contacted via e-mail.