C++ Arrays
Introduction
Arrays are one of the most fundamental data structures in programming. In C++, an array is a collection of elements of the same data type, stored in contiguous memory locations. This makes arrays efficient for storing and accessing multiple values of the same type under a single variable name.
Think of an array as a collection of boxes lined up in a row, where each box can hold one item of a specific type. Each box has an index number, starting from 0, which allows you to access its contents.
- Fixed size (determined at compile time for standard arrays)
- Homogeneous elements (all elements must be of the same data type)
- Contiguous memory allocation
- Zero-indexed (first element is at index 0)
Declaring and Initializing Arrays
Basic Array Declaration
The syntax for declaring an array in C++ is:
dataType arrayName[arraySize];
For example, to declare an array of 5 integers:
int numbers[5];
This creates an array named numbers
that can hold 5 integers.
Array Initialization
There are several ways to initialize arrays in C++:
1. Initialize at declaration
int numbers[5] = {10, 20, 30, 40, 50};
2. Initialize without specifying size
int numbers[] = {10, 20, 30, 40, 50}; // Size is determined automatically (5)
3. Initialize specific elements
int numbers[5] = {0}; // Initialize first element to 0, rest defaults to 0
4. Initialize all elements to zero
int numbers[5] = {}; // All elements initialized to 0
Example: Array Declaration and Initialization
#include <iostream>
using namespace std;
int main() {
// Method 1: Declaration and then assignment
int scores[5];
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
scores[3] = 95;
scores[4] = 88;
// Method 2: Declaration with initialization
int grades[5] = {90, 85, 88, 75, 92};
// Method 3: Let compiler determine the size
int values[] = {1, 2, 3, 4, 5, 6, 7};
// Display the elements of the grades array
cout << "Grades: ";
for(int i = 0; i < 5; i++) {
cout << grades[i] << " ";
}
cout << endl;
return 0;
}
Output:
Grades: 90 85 88 75 92
Accessing Array Elements
Each element in an array is accessed using its index. In C++, array indices start at 0, meaning the first element is at index 0, the second at index 1, and so on.
int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[0]; // Outputs: 10 (first element)
cout << numbers[4]; // Outputs: 50 (last element)
Example: Accessing and Modifying Array Elements
#include <iostream>
using namespace std;
int main() {
int temperatures[7] = {72, 75, 73, 78, 71, 69, 74};
cout << "Temperature on day 3: " << temperatures[2] << endl;
// Modify an element
temperatures[2] = 80;
cout << "Updated temperature on day 3: " << temperatures[2] << endl;
// Calculate average temperature
int sum = 0;
for(int i = 0; i < 7; i++) {
sum += temperatures[i];
}
double average = static_cast<double>(sum) / 7;
cout << "Average temperature: " << average << endl;
return 0;
}
Output:
Temperature on day 3: 73
Updated temperature on day 3: 80
Average temperature: 74.1429
Common Array Operations
1. Finding the Length of an Array
In C++, the size of an array can be calculated using the sizeof
operator:
int numbers[5] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]);
cout << "Array length: " << length << endl; // Outputs: 5
2. Iterating Through an Array
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
cout << "Using a for loop:" << endl;
for(int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
cout << "Using a range-based for loop (C++11 and later):" << endl;
for(int num : numbers) {
cout << num << " ";
}
cout << endl;
return 0;
}
Output:
Using a for loop:
1 2 3 4 5
Using a range-based for loop (C++11 and later):
1 2 3 4 5
3. Finding Max and Min Values
#include <iostream>
#include <algorithm> // for std::max_element and std::min_element
using namespace std;
int main() {
int values[] = {45, 67, 23, 90, 15, 56};
int size = sizeof(values) / sizeof(values[0]);
// Method 1: Using a loop
int max_val = values[0];
int min_val = values[0];
for(int i = 1; i < size; i++) {
if(values[i] > max_val) {
max_val = values[i];
}
if(values[i] < min_val) {
min_val = values[i];
}
}
cout << "Using a loop - Max: " << max_val << ", Min: " << min_val << endl;
// Method 2: Using standard library algorithms
int* max_element_ptr = max_element(values, values + size);
int* min_element_ptr = min_element(values, values + size);
cout << "Using algorithms - Max: " << *max_element_ptr << ", Min: " << *min_element_ptr << endl;
return 0;
}
Output:
Using a loop - Max: 90, Min: 15
Using algorithms - Max: 90, Min: 15
Multi-dimensional Arrays
C++ supports multi-dimensional arrays. A 2D array is like a table with rows and columns:
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
This creates a 3×4 matrix (3 rows, 4 columns).
Accessing Elements in a 2D Array
cout << matrix[1][2]; // Outputs: 7 (element at row 1, column 2)
Example: Working with 2D Arrays
#include <iostream>
using namespace std;
int main() {
// Declare and initialize a 3x3 matrix
int grid[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Display the matrix
cout << "Matrix:" << endl;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
// Calculate the sum of all elements
int sum = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
sum += grid[i][j];
}
}
cout << "Sum of all elements: " << sum << endl;
return 0;
}
Output:
Matrix:
1 2 3
4 5 6
7 8 9
Sum of all elements: 45
Common Pitfalls and Considerations
1. Array Bounds
C++ does not automatically check if an array index is valid. Accessing an array out of its bounds leads to undefined behavior.
int numbers[5] = {1, 2, 3, 4, 5};
cout << numbers[10]; // Undefined behavior - accessing beyond array bounds
2. Arrays are Not Resizable
Once declared, standard C++ arrays cannot change their size. For dynamic sizing, consider using std::vector
from the C++ Standard Library.
3. Arrays in Functions
When you pass an array to a function, you're actually passing a pointer to the first element. The function can modify the original array.
#include <iostream>
using namespace std;
void modifyArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
cout << "Before modification: ";
for(int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
modifyArray(numbers, 5);
cout << "After modification: ";
for(int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
Output:
Before modification: 1 2 3 4 5
After modification: 2 4 6 8 10
Real-world Applications
Arrays are foundational in programming and have numerous practical applications:
1. Temperature Tracking
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
const int DAYS = 7;
double temperatures[DAYS];
string days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
// Collect temperature data
cout << "Enter the temperature for each day of the week:" << endl;
for(int i = 0; i < DAYS; i++) {
cout << days[i] << ": ";
cin >> temperatures[i];
}
// Calculate average temperature
double sum = 0;
for(int i = 0; i < DAYS; i++) {
sum += temperatures[i];
}
double average = sum / DAYS;
// Find highest and lowest temperatures
double highest = temperatures[0];
double lowest = temperatures[0];
int highestDay = 0, lowestDay = 0;
for(int i = 1; i < DAYS; i++) {
if(temperatures[i] > highest) {
highest = temperatures[i];
highestDay = i;
}
if(temperatures[i] < lowest) {
lowest = temperatures[i];
lowestDay = i;
}
}
// Display results
cout << fixed << setprecision(1);
cout << "\nWeekly Temperature Report:" << endl;
cout << "Average temperature: " << average << "°F" << endl;
cout << "Highest temperature: " << highest << "°F on " << days[highestDay] << endl;
cout << "Lowest temperature: " << lowest << "°F on " << days[lowestDay] << endl;
return 0;
}
This program collects temperature data for a week, then analyzes it to find the average, highest, and lowest temperatures.
2. Simple Game Board
#include <iostream>
using namespace std;
int main() {
char board[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
// Make some moves (X at (0,0), O at (1,1), X at (2,2))
board[0][0] = 'X';
board[1][1] = 'O';
board[2][2] = 'X';
// Display the board
cout << "Tic-Tac-Toe Board:" << endl;
for(int i = 0; i < 3; i++) {
cout << " ";
for(int j = 0; j < 3; j++) {
cout << board[i][j];
if(j < 2) cout << " | ";
}
cout << endl;
if(i < 2) cout << "-----------" << endl;
}
return 0;
}
Output:
Tic-Tac-Toe Board:
X | |
-----------
| O |
-----------
| | X
This simple example shows how a 2D array can represent a game board for Tic-Tac-Toe.
Summary
Arrays in C++ are a powerful and efficient way to store collections of data of the same type. In this tutorial, we covered:
- Declaration and initialization of arrays
- Accessing and modifying array elements
- Common array operations (finding length, iterating, finding max/min)
- Multi-dimensional arrays
- Common pitfalls and considerations
- Real-world applications of arrays
As you continue to learn C++, arrays will serve as a foundation for understanding more complex data structures such as vectors, lists, and maps.
Additional Resources
- cppreference - Array declaration
- C++ Standard Library - std::array
- C++ Standard Library - std::vector (when you need resizable arrays)
Exercises
-
Array Sum and Average: Write a program that calculates the sum and average of elements in an array.
-
Element Search: Write a function that searches for a specific element in an array and returns its index (or -1 if not found).
-
Array Reversal: Write a program that reverses the elements of an array without using a second array.
-
Matrix Addition: Create a program that adds two 3×3 matrices and stores the result in a third matrix.
-
Temperature Conversion: Create an array of Celsius temperatures, then convert each to Fahrenheit and store in a new array.
Good luck with your C++ journey! Arrays are just the beginning of your adventure into data structures and algorithms.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)