Arrays c++


In C++, an array is a collection of variables of the same type that are stored contiguously in memory.

 The variables within an array are accessed by their index.

which is an integer value that starts at 0 for the first element and goes up to the size of the array minus one for the last element.


Here's an example of how to declare and initialize an array in C++:


less code


int myArray[5]; 

// declares an array of 5 integers myArray[0] = 1; 

// assigns 1 to the first element of the array myArray[1] = 2; 

// assigns 2 to the second element of the array myArray[2] = 3;

 // assigns 3 to the third element of the array myArray[3] = 4; 

// assigns 4 to the fourth element of the array myArray[4] = 5;

 // assigns 5 to the fifth element of the array // alternatively, you can initialize the array during declaration int myArray2[5] = {1, 2, 3, 4, 5}; 


You can also use a loop to iterate over the elements of an array:


cCopy code


for (int i = 0; 

i < 5; 

i++)

 { 

std::cout << myArray[i] << std::endl; 

// prints out each element of the array

 } 


In C++, arrays can be passed to functions as arguments, and they can also be returned from functions.

 However, when passed as an argument, the size of the array must also be passed, as it is not automatically included with the array itself.