Arrays
An Array is a compound data type or a structured data type. Basically an array is a data type made up of other data types. All elements are of the same type when using arrays. Each element can be accessed directly.
Why Use Arrays
Arrays allow you to tell the compiler to give you a collection of as many elements as you want and give the entire collection a single name.
Array Characteristics
Fixed size
Elements are all the same type
Stored contiguously in memory
Individual elements can be accessed by their position or index
First element
is atindex 1
Last element
is atindex size -1
No checking to see if you are out of bounds
Always initialize arrays
Very efficient
Iteration (looping) is often used to process
Examples
In programming, one of the frequently arising problem is to handle numerous data of same type.
Consider this situation, you are taking a survey of 100 people and you have to store their age. To solve this problem in C++, you can create an integer array having 100 elements.
An array is a collection of data that holds fixed number of values of same type. For example:
Here, the age array can hold maximum of 100 elements of integer type.
The size and type of arrays cannot be changed after its declaration.
How to declare an array in C++?
For example,
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values.
Elements of an Array and How to access them?
You can access elements of an array by using indices.
Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and so on.
Few key notes:
Arrays have 0 as the first index not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element,
(n-1)
index is used. In this example, mark[4] is the last element.Suppose the starting address of
mark[0]
is 2120d. Then, the next address,a[1]
, will be 2124d, address ofa[2]
will be 2128d and so on. It's because the size of float is 4 bytes.
How to initialize an array in C++ programming?
It's possible to initialize an array during declaration. For example,
Another method to initialize array during declaration:
Here,
How to insert and print array elements?
C++ program to store and calculate the sum of 5 numbers entered by the user using arrays.
Output
Things to remember when working with arrays in C++
Suppose you declared an array of 10 elements. Let's say,
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).
Before going further, checkout these C++ array articles:
Check out these examples to learn more:
Last updated