CPP Tutorial



C++ ARRAYS


Arrays in C++

An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays help you store multiple values in a single variable, instead of declaring separate variables for each value.


Declaring Arrays

To declare an array, specify the data type, array name, and size (number of elements) inside square brackets [].

data_type array_name[array_size];
  

Example:

int numbers[5];  // declares an array of 5 integers
  

Initializing Arrays

You can initialize an array during declaration by providing a list of values inside curly braces {}.

int numbers[5] = {10, 20, 30, 40, 50};
  

If you provide fewer values than the size, the remaining elements are initialized to zero.

int arr[5] = {1, 2};  // arr = {1, 2, 0, 0, 0}
  

Accessing Array Elements

Access elements of an array using the index inside square brackets. Note that array indices start at 0.

int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[0];  // Outputs: 10
cout << numbers[3];  // Outputs: 40
  

Modifying Array Elements

You can assign a new value to any element by accessing it via its index.

numbers[2] = 100;  // Change the 3rd element (index 2) to 100
  

Looping Through Arrays

You can iterate through array elements using loops, commonly a for loop.

for(int i = 0; i < 5; i++) {
    cout << "Element " << i << ": " << numbers[i] << endl;
}
  

Important Points

  • Array size must be a constant and known at compile time (for basic arrays).
  • Accessing elements outside the array bounds causes undefined behavior (may crash or give wrong data).
  • Arrays store elements contiguously in memory, so elements are accessed efficiently.
  • C++ also provides std::array and std::vector for safer and dynamic arrays (advanced topics).

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review