C++ Array


The array, which stores a fixed-size sequential collection of elements of the same type.

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.


Declaring Arrays

To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows:

type  arrayName [ arraySize ];

Initializing Arrays

You can initialize C++ array elements either one by one or using a single statement as follows:

double salary[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array.

double salary[9];

Example

#include<iostream>
	using namespace std;
int main()
	{
		int a[4];
		int i;
		for ( i = 0; i < 4; i++ )
			a[i] = 0;
			for ( i = 0; i < 4; i++ )
			cout << a[i] << '\n';
		return 0;
	}
Multi-dimensional arraysPointer to an array
C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. View You can generate a pointer to the first element of an array by simply specifying the array name, without any index. View
Passing arrays to functionsReturn array from functions
You can pass to the function a pointer to an array by specifying the array's name without an index. View C++ allows a function to return an array. View

Share this article on