Array in C++
An array is a collection of similar data items stored at contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
For example, an array containing 5 integer values of type int called foo could be represented as:
Therefore, the foo array, with five elements of type int, can be declared as:
|
Initializing arrays:
By writing int arr[ ]={ 1,3,5 }; , we are initializing the array.
We declare an array like int arr[3];, But we need to assign the values to it separately. Because 'int arr[3];' will definitely allocate the space of 3 integers in the memory but there are no integers in that.
To assign values to the array, assign a value to each of the elements of the array:
arr[0]=1;
arr[1]=3;
arr[2]=5;
It is the same like we are declaring some variables then assign values to them:
x=1;
y=2;
z=3;
Thus, there are two ways to initialize:
First
|
and second is declaring the array first and then assigning the values to its elements.
int arr[3];
|
Example:
|
Output:
Enter first student marks
63
Enter second student marks
58
Enter third student marks
44
Average marks : 55
You access an array element by referring to the index number.
Array elements are accessed by using an integer index. Array index starts with 0 and goes to the size of the array minus 1.
The name which can be used to refer to each element is the following:
For example, the following statement stores the value 75 in the third element of arr[]:
arr [2]=36;
and, for example, the following copies the value of the third element of arr[] to a variable called x:
x=arr[2];
For example:
|
There are three types of Arrays:
1. One Dimensional Array:
In this type of array, it stores elements in a single dimension. And, In this array, a single specification is required to describe elements of the array.
#include <iostream> |
Output:
1 2 5 7 3 |
Two Dimensional Array:
In this, two indexes describe each element, the first index represents a row, and the second index represents a column.
Following is an example of 2D Array:
#include <iostream> |
Output:
1 2 3 2 4 6 3 6 9 |
Multidimensional Array:
A plain example of multidimensional array is a 2-d array. A two- dimensional array also falls under the category of multidimensional array. This multidimensional array can have any number of dimensions.
Syntax for declaring:
Datatype arr_nm[size1][size2]......[size n];
Example:
int array[5][10][4];