C++ Arrays Tutorial
Arrays in C++ are used to store multiple values of the same type in a single variable. This tutorial explains how to use arrays efficiently with examples.
1. Declaring an Array
An array is declared using the syntax:
int numbers[5]; // Declares an array of 5 integers
Here, numbers can hold 5 integers, indexed from 0 to 4.
2. Initializing an Array
You can initialize an array at the time of declaration:
int numbers[5] = {10, 20, 30, 40, 50};
Elements are assigned in the order specified in the initializer list.
3. Accessing Array Elements
Use the index to access or modify elements:
#include <iostream>
using namespace std;
int main() {
int numbers[3] = {10, 20, 30};
cout << "First element: " << numbers[0] << endl; // Access
numbers[2] = 50; // Modify
cout << "Modified third element: " << numbers[2] << endl;
return 0;
}
4. Multidimensional Arrays
C++ supports arrays with multiple dimensions:
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
cout << "Element at (1,2): " << matrix[1][2] << endl;
return 0;
}
This example demonstrates a 2x3 array. Access elements using matrix[row][column].
5. Iterating Over Arrays
Use loops to process arrays:
#include <iostream>
using namespace std;
int main() {
int numbers[4] = {5, 10, 15, 20};
for (int i = 0; i < 4; i++) {
cout << "Element " << i << ": " << numbers[i] << endl;
}
return 0;
}
This example uses a for loop to print all array elements.
6. Common Mistakes
- Accessing out-of-bounds indices, leading to undefined behavior.
- Not initializing arrays, which can result in garbage values.
×