Array

Array

Arra

An array in C++ is a collection of elements of the same data type, stored in contiguous memory locations. The elements can be accessed using their index (position) in the array, starting from zero.

 syntax:

				
					data_type array_name[array_size];

​
				
			

Here, data_type is the data type of the elements in the array, array_name is the name of the array, and array_size is the number of elements in the array.

For example, to declare an array of integers with five elements, you can use the following code:

				
					int my_array[5];

​
				
			

You can also initialize the elements  at the time of declaration using the following syntax:

				
					data_type array_name[array_size] = {element1, element2, ...,elementN}; 
				
			

For example, to declare and initialize an array of integers with five elements, you can use the following code:

				
					int my_array[5] = {1, 2, 3, 4, 5}; 

​
				
			

You can access the elements by using their index, like this:

				
					my_array[0] = 10; // set the first element to 10 

int x = my_array[2]; // get the third element

​
				
			

It’s important to note that C++ arrays are zero-indexed, meaning the first element is at index 0, the second element is at index 1, and so on. You should also be careful not to access elements outside the bounds of the array, as this can cause undefined behavior and potentially crash your program.

Join To Get Our Newsletter
Spread the love