Array Data Structure

๐ Introduction to Arrays
An array is a basic data structure used in programming. It is a collection of elements stored at continuous memory locations. All the elements in an array are of the same type, such as integers or characters.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
๐ข Why Use Arrays?
Arrays make it easy to:
Store a list of values.
Access elements using index numbers.
Use loops to process all elements easily.
Reduce the number of variables in a program.
For example, instead of writing:
int a = 10, b = 20, c = 30;
You can write:
int arr[3] = {10, 20, 30};
๐งฑ Features of an Array
Fixed Size:
The size of an array is defined when it is created and cannot be changed.Indexed Access:
You can access any element by its index. Indexing starts from 0.Same Data Type:
All items in the array are of the same type (e.g., all integers or all floats).
๐ Types of Arrays
1. One-Dimensional Array
A simple list of elements.
int numbers[5] = {1, 2, 3, 4, 5};
2. Two-Dimensional Array (Matrix)
It stores data in rows and columns.
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
3. Multi-Dimensional Arrays
An extension of 2D arrays. Rarely used in beginner-level coding.
๐ Accessing Array Elements
You can access or update an array element using its index.
int arr[3] = {10, 20, 30};
cout << arr[1]; // Output: 20
arr[2] = 100; // Update value at index 2
๐ Looping Through an Array
You can use loops like for
to go through all elements:
for(int i = 0; i < 3; i++) {
cout << arr[i] << " ";
}
โ ๏ธ Limitations of Arrays
Fixed size: Once declared, you cannot change the array size.
Cannot insert or delete easily like in other structures (e.g., vector, list).
Memory may be wasted if you don't use all the elements.
โ Conclusion
Arrays are one of the most important and simple data structures. They are useful when you need to store a fixed number of items and want fast access using indexes. Understanding arrays is a strong foundation for learning other complex data structures like linked lists, stacks, and queues.
Subscribe to my newsletter
Read articles from ANSHU directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
