arrays in cpp
#arrays in cpp
Introduction
Arrays are a fundamental data structure in C++ used to store multiple values of the same type in a single variable. They are stored in contiguous memory locations and allow efficient access using an index.
An array is a collection of elements of the same data type stored under a single name. Each element is accessed by its index (position) starting from 0.
Key Points:
Fixed size (defined at compile-time)
Elements must be of the same data type
Random access using indices
#include <iostream>
using namespace std;
int main() {
// Declaration
int numbers[5];
// Initialization
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Access elements
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
return 0;
}
Output:
10 20 30 40 50
#include <iostream>
using namespace std;
int main() {
int marks[5] = {90, 85, 78, 92, 88};
for (int i = 0; i < 5; i++) {
cout << "Marks[" << i << "] = " << marks[i] << endl;
}
return 0;
}
Output:
Marks[0] = 90
Marks[1] = 85
Marks[2] = 78
Marks[3] = 92
Marks[4] = 88
One-Dimensional Array – Simple list of elements
Two-Dimensional Array (Matrix) – Table-like structure (rows and columns)
Multi-Dimensional Arrays – Arrays with more than two dimensions
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
1 2 3
4 5 6
Easy to store and manage large sets of data
Fast random access using indices
Contiguous memory allocation improves performance
Fixed size (cannot be changed at runtime)
All elements must be of the same data type
Insertion and deletion operations are costly
Arrays are a simple yet powerful data structure in C++. They allow you to group multiple values of the same type and access them efficiently using indices. Mastering arrays is essential before learning advanced data structures like vectors and linked lists.