An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).
For example, to store the marks of a student in 5 subjects, we can create an array of integers, say marks[5].
Definition:
An array is a group of variables that share the same name and are referred to by a common name. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Each item in an array is called an element, and each element is accessed by its numerical index. As an example, consider the following array:
int marks[5];
Here, marks is an array of 5 integers. The elements of the array are marks[0], marks[1], marks[2], marks[3], and marks[4].
Examples:
- Initializing an array:
int marks[5] = {1, 2, 3, 4, 5};
Here, marks is an array of 5 integers, and it is initialized with the values 1, 2, 3, 4, and 5.
- Accessing array elements:
To access the elements of an array, we use the index of the element in the array. For example:
int x = marks[2];
Here, x will be assigned the value 3, which is the value at index 2 in the marks array.
- Modifying array elements:
To modify the value of an element in an array, we simply use the index of the element and assign it a new value. For example:
marks[3] = 10;
Here, the value at index 3 in the marks array is changed to 10.
- Getting the size of an array:
To get the size of an array in C++, we can use the sizeof operator. For example:
int size = sizeof(marks)/sizeof(marks[0]);
Here, size will be assigned the value 5, which is the size of the marks array.
- Multidimensional arrays:
Arrays can also be multidimensional. A multidimensional array is an array of arrays. For example:
int multi[2][3] = {{1, 2, 3}, {4, 5, 6}};
Here, multi is a 2×3 array, and it is initialized with the values 1, 2, 3, 4, 5, and 6. The elements of the array are multi[0][0], multi[0][1], multi[0][2], multi[1][0], multi[1][1], and multi[1][2].
Quiz:
- What is an array?
- How do you access the elements of an array?
- How do you modify the elements of an array?
- How do you get the size of an array?
- Can arrays be multidimensional?
- Can you store elements of different data types in the same array?
- What is the first element in an array with indexing starting at 1?
- What is the last element in an array with 5 elements and indexing starting at 1?
- How do you initialize an array in C