C++ Arrays
Storing and managing multiple values in C++
📚 What are C++ Arrays?
C++ arrays are collections that store multiple values of the same type in consecutive memory locations, allowing efficient access and manipulation of related data elements.
#include <iostream>
using namespace std;
int main() {
// Declare and initialize an array
int numbers[5] = {10, 20, 30, 40, 50};
// Access and print array elements
for (int i = 0; i < 5; i++) {
cout << "Element " << i << ": " << numbers[i] << endl;
}
return 0;
}
Output:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
Key Array Concepts
Declaration
Define array size and type
int arr[5]; // 5 integers
Indexing
Access elements by position
arr[0] = 10; // first element
Initialization
Set initial values
int arr[3] = {1, 2, 3};
Iteration
Loop through all elements
for (int i = 0; i < size; i++)
🔹 Array Declaration and Initialization
Arrays in C++ are fixed-size collections declared with a type and size, offering multiple initialization
methods. You can list values directly, like int scores[] = {85, 92, 78, 96}, or initialize
with strings: char names[] = {"Alice", "Bob", "Charlie"}. These methods allocate contiguous memory,
ensuring fast, sequential access. Understanding declaration syntax is foundational for managing data sets, from
simple lists to complex buffers, in a memory-efficient manner.
#include <iostream>
using namespace std;
int main() {
// Method 1: Declare then assign
int scores[4];
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
scores[3] = 96;
// Method 2: Declare and initialize together
string names[3] = {"Alice", "Bob", "Charlie"};
// Method 3: Let compiler determine size
double prices[] = {19.99, 25.50, 12.75, 8.99};
cout << "Scores: ";
for (int i = 0; i < 4; i++) {
cout << scores[i] << " ";
}
cout << endl;
cout << "Names: ";
for (int i = 0; i < 3; i++) {
cout << names[i] << " ";
}
cout << endl;
return 0;
}
Output:
Scores: 85 92 78 96
Names: Alice Bob Charlie
🔹 Accessing Array Elements
Array elements are accessed via zero-based indexing, allowing both reading and modification of
values. For a weekly temperature array, you might read temps[0] as 22°C (Monday) and
update temps[2] from 28°C to 26°C (Wednesday). You can also iterate to find extremes, like identifying
the highest temperature (e.g., 30°C). This direct index-based manipulation is central to algorithms like searching,
sorting, and data transformation in C++ programs.
#include <iostream>
using namespace std;
int main() {
int temperatures[7] = {22, 25, 28, 30, 27, 24, 21};
cout << "Weekly temperatures:" << endl;
cout << "Monday: " << temperatures[0] << "°C" << endl;
cout << "Tuesday: " << temperatures[1] << "°C" << endl;
cout << "Wednesday: " << temperatures[2] << "°C" << endl;
// Modify an element
temperatures[2] = 26; // Change Wednesday's temperature
cout << "Updated Wednesday: " << temperatures[2] << "°C" << endl;
// Find highest temperature
int highest = temperatures[0];
for (int i = 1; i < 7; i++) {
if (temperatures[i] > highest) {
highest = temperatures[i];
}
}
cout << "Highest temperature: " << highest << "°C" << endl;
return 0;
}
Output:
Weekly temperatures:
Monday: 22°C
Tuesday: 25°C
Wednesday: 28°C
Updated Wednesday: 26°C
Highest temperature: 30°C
🔹 Array Size and Loops
Determining array size and iterating with loops is essential for processing all elements
dynamically. Using sizeof(array)/sizeof(element) calculates the count (e.g., 6). Loops
then traverse each item to perform operations like printing elements {5, 10, 15, 20, 25, 30}, computing
their sum (105), or finding the average (17.5). This pattern is crucial for tasks like data aggregation, filtering,
and applying functions across collections without manual, per-element code.
#include <iostream>
using namespace std;
int main() {
int numbers[] = {5, 10, 15, 20, 25, 30};
// Calculate array size
int size = sizeof(numbers) / sizeof(numbers[0]);
cout << "Array size: " << size << endl;
// Print all elements
cout << "Array elements: ";
for (int i = 0; i < size; i++) {
cout << numbers[i] << " ";
}
cout << endl;
// Calculate sum and average
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
double average = (double)sum / size;
cout << "Sum: " << sum << endl;
cout << "Average: " << average << endl;
return 0;
}
Output:
Array size: 6
Array elements: 5 10 15 20 25 30
Sum: 105
Average: 17.5
🔹 Multi-dimensional Arrays
Multi-dimensional arrays, like 2D matrices, organize data in rows and columns for complex
representations. Declared as int matrix[3][4], they can store tabular data. Access uses
two indices: matrix[row][column], such as retrieving the value 7 from row 1, column 2. These structures
are fundamental in graphics, game grids, scientific computations, and any application requiring coordinate-based
data access, enabling efficient modeling of layered information.
#include <iostream>
using namespace std;
int main() {
// 2D array (3 rows, 4 columns)
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
cout << "2D Array (Matrix):" << endl;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
cout << matrix[row][col] << "\t";
}
cout << endl;
}
// Access specific element
cout << "Element at row 1, column 2: " << matrix[1][2] << endl;
return 0;
}
Output:
2D Array (Matrix):
1 2 3 4
5 6 7 8
9 10 11 12
Element at row 1, column 2: 7