C++ C++ Tutorial C++ Functions C++ Classes



CPP Arrays

C++ arrays are a collection of similar data types that are stored in contiguous memory locations. They are used to store a fixed-size sequential collection of elements of the same type. Arrays are an essential part of any programming language, and C++ provides a robust and efficient way of working with arrays.

Arrays in C++ are declared using the following syntax:

type arrayName[arraySize];

Here, type is the data type of the elements that the array will hold, arrayName is the name of the array, and arraySize is the number of elements that the array can hold.

For example, to declare an array of integers that can hold 5 elements, we can use the following code:

int myArray[5];

Once an array is declared, we can access its elements using their index. The index of the first element in an array is always 0, and the index of the last element is always one less than the size of the array. For example, to access the first element of the myArray array, we can use the following code:

int firstElement = myArray[0];

We can also assign values to the elements of an array using their index. For example, to assign the value 10 to the first element of the myArray array, we can use the following code:

myArray[0] = 10;

C++ also provides several functions that can be used to work with arrays. For example, the sizeof function can be used to determine the size of an array in bytes. The std::begin and std::end functions can be used to get pointers to the beginning and end of an array, respectively.

Here is an example program that demonstrates the use of arrays in C++:

#include <iostream>

int main() {
    int myArray[5] = {1, 2, 3, 4, 5};

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

    return 0;
}

In this program, we declare an array of integers called myArray that can hold 5 elements. We then initialize the array with the values 1, 2, 3, 4, and 5. Finally, we use a for loop to iterate over the elements of the array and print their values to the console.

Arrays are an essential part of any programming language, and C++ provides a robust and efficient way of working with arrays. By understanding how arrays work in C++, you can write more efficient and effective code.

References

Activity