Introduction to arrays in C++

Arrays in C++ and other languages is a collection of elements of the same variable type that are placed in contiguous memory locations that can be individually referenced. The way it can be individually referenced is by adding an index to the identifier.

Normally one dimensional arrays are more common because they are useful for holding characters and string variables.

The general form of declaring a one dimensional array is:

variable_type variable_name[size];

For example, an array containing five integer values of the variable type int could be represented visually as:

array diagram

The sample code below will output the elements in the array

one dimesional array code 1

Output from the example code above. As you can see, it just outputs the array index numbers.

one dimensional array code 1 output

Setting and displaying array values 

By default, regular arrays are left with no set values. The elements in an array can be set to specific values when it is declared with braces like the example below:

int sample[5] = {10,20,50,100,200};

The elements then can be outputted on the screen with the help of the for loop code. Firstly you must output the array variable name which we named “sample” then you must type in “[i]” after it so the for loop elements are displayed.

one dimensional array code 2

Output of the set array values

one dimensional array code 2 output

Share this post