Until now, we have focused on variables that can hold a single value. For instance, we can have a variable to store a student’s roll number and another to hold a student’s final grade. But what if we have a class of hundred students? Can we manage a hundred variables to store roll numbers and a hundred additional to store grades? Suppose we want to calculate the average grade. Will the mathematical expression include the addition of a hundred variables? The example clarifies that managing several variables is not a feasible solution. To address the problem, we use arrays.

Arrays

In C++, an array is a collection of similar data types under the same name.

But what does this mean? Imagine an array as a row of houses, all identical and lined up next to each other on a street. Each house can hold a family, and each house is numbered sequentially.

In the context of programming, an array is like this row of houses, where each house represents a slot in memory that can hold a piece of data (like an int, char, float, or any other data type). The array itself is like the street, and the index of the array is like the number on each house.

Let's have a look at some of the keypoints of arrays:

  1. Fixed Size: Just as a street has a fixed number of houses, an array has a fixed number of elements, determined when the array is declared. For example, If we declare an array of 5 numbers, it’s like saying there are five houses on the street.

  2. Homogeneous Data: All houses on the street are of the same type; similarly, all elements in an array must be of the same data type (e.g., all integers, all characters). For example, if we have an array of 5 integers, it means that we have 5 mailboxes and every mailbox can only hold an integer letter.

  3. Indexing: Just like houses have addresses (house numbers), elements in an array are accessed using indices, which start at 0 and go up to teh size of teh array minus one.

  4. Random Access: We can directly go to any house without visiting others, just like that, we can access any element in an array using its index without needing to traverse the array.

  5. Contiguous Memory Allocation: Houses on a street are next to each other, just as elements in an array are stored in consecutive memory locations. This entire row of houses (array) is managed as a single entity, making it easier to handle a collection of related data. For example, when we declare an array numbers with 5 elemnts, memory for all five elements are allocated at once, similar to reserving space for five houses.

Declaring arrays

In C++, arrays are declared in the following way​:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy