#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[0] << endl;
cout << numbers[1] << endl;
cout << numbers[2] << endl;
return 0;
}Arrays in C++: Declaring, Initializing, Accessing, and Updating Elements
Direct Answer & Core Concept
Arrays are an important part of C++ programming. They allow you to store multiple values of the same data type using a single variable name.
Instead of declaring separate variables for every value, you can use an array to organize related data and access individual elements using their indexes.
Detailed Explanation & Mechanics
1. What Is an Array in C++?
An array is a collection of elements of the same data type stored in a sequence of memory locations.
Each element is accessed using an index.
In a traditional C++ array, indexing starts from 0.
Example
Output:
10
20
30Explanation
numbersis the array name.intspecifies the data type.5specifies the number of elements.{10, 20, 30, 40, 50}initializes the array.numbers[0]accesses the first element.
An array is useful when you need to store and process multiple related values.
2. Array Declaration in C++
Before using an array, you generally declare it by specifying its data type, name, and size.
Syntax
data_type array_name[array_size];Examples
int marks[5];
float prices[10];
char letters[4];
double salaries[6];Explanation
| Declaration | Meaning |
|---|---|
int marks[5] | Array of 5 integers |
float prices[10] | Array of 10 floating-point values |
char letters[4] | Array of 4 characters |
double salaries[6] | Array of 6 double-precision values |
The size of a built-in array must be a compile-time constant expression in standard C++.
Example
#include <iostream>
using namespace std;
int main() {
int marks[5];
marks[0] = 80;
marks[1] = 75;
marks[2] = 90;
marks[3] = 85;
marks[4] = 95;
cout << marks[0] << endl;
cout << marks[4] << endl;
return 0;
}Output:
80
953. Array Initialization in C++
Array initialization means assigning initial values to the elements when the array is created.
C++ supports several ways to initialize arrays.
1. Initialize all elements
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
return 0;
}Output:
10
20
30
40
502. Initialize without specifying the size
You can let the compiler determine the array size from the number of initial values.
int numbers[] = {
10, 20, 30, 40
}
;The compiler determines that the array contains four elements.
3. Partial initialization
You can provide fewer initial values than the declared array size.
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
return 0;
}Output:
10
20
0
0
0The remaining elements are initialized to zero.
4. Initialize all elements to zero
int numbers[5] = {
}
;All five elements are initialized to zero.
You can also write:
int numbers[5] = {
0
}
;5. Initialize using a loop
#include <iostream>
using namespace std;
int main() {
int numbers[5];
for (int i = 0; i < 5; i++) {
numbers[i] = (i + 1) * 10;
}
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
return 0;
}Output:
10
20
30
40
504. Accessing Array Elements in C++
You can access an individual array element using its index inside square brackets.
Syntax
array_name[index];Remember that array indexing starts from 0.
For an array containing five elements, valid indexes are 0 through 4.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << "First element: " << numbers[0] << endl;
cout << "Second element: " << numbers[1] << endl;
cout << "Third element: " << numbers[2] << endl;
cout << "Last element: " << numbers[4] << endl;
return 0;
}Output:
First element: 10
Second element: 20
Third element: 30
Last element: 50Array index reference
| Index | Element | Value |
|---|---|---|
| 0 | numbers[0] | 10 |
| 1 | numbers[1] | 20 |
| 2 | numbers[2] | 30 |
| 3 | numbers[3] | 40 |
| 4 | numbers[4] | 50 |
Important: Accessing an element outside the valid array range causes undefined behavior.
5. Updating Array Elements in C++
You can change an array element by assigning a new value to its index.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
numbers[0] = 100;
numbers[2] = 300;
numbers[4] = 500;
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
return 0;
}Output:
100
20
300
40
500Explanation
numbers[0] = 100updates the first element.numbers[2] = 300updates the third element.numbers[4] = 500updates the fifth element.
The array size remains unchanged.
6. Traversing an Array Using a for Loop
Traversing means visiting each array element one by one.
A for loop is commonly used to process all array elements.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
return 0;
}Output:
10
20
30
40
50How does it work?
The loop starts with
i = 0.It checks whether
iis less than5.It prints the element at
numbers[i].It increments
i.The loop stops when
ireaches5.
This is one of the most common ways to process an array.
7. Traversing an Array Using a while Loop
You can also use a while loop to access array elements.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int i = 0;
while (i < 5) {
cout << numbers[i] << endl;
i++;
}
return 0;
}Output:
10
20
30
40
50The loop continues until every element has been processed.
8. Traversing an Array Using a Range-Based for Loop
C++11 introduced the range-based for loop.
It provides a simpler way to visit every element in an array.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
for (int value : numbers) {
cout << value << endl;
}
return 0;
}Output:
10
20
30
40
50Modifying elements with a reference
If you want to modify the original elements, use a reference in the range-based loop.
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30};
for (int& value : numbers) {
value *= 2;
}
for (int value : numbers) {
cout << value << endl;
}
return 0;
}Output:
20
40
60Using int value would modify only a copy. Using int& value allows the loop to update the original array elements.
9. Finding the Length of an Array
For a built-in array in the same scope where it is still an array, you can use the sizeof operator to calculate its number of elements.
Syntax
sizeof(array) / sizeof(array[0])Example
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
cout << "Array size: " << size << endl;
return 0;
}Output:
Array size: 5Explanation
sizeof(numbers)returns the total size of the array in bytes.sizeof(numbers[0])returns the size of one element.Dividing the total size by the element size gives the number of elements.
Modern C++ alternative:
You can use std::size() from the <iterator> header in C++17 and later.
#include <iostream>
#include <iterator>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
cout << size(numbers) << endl;
return 0;
}Output:
5Remember that a built-in array passed to a function as an ordinary array parameter is adjusted to a pointer. In that function, sizeof(parameter) gives the pointer size, not the original array size. Pass the size separately or use a suitable container or array reference.
10. Finding the Sum of Array Elements
You can use a loop to calculate the sum of all array elements.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "Sum: " << sum << endl;
return 0;
}Output:
Sum: 150Explanation
The program starts with sum = 0 and adds each array element to the total.
This approach is useful for calculating marks, sales totals, expenses, and other numerical data.
11. Finding the Largest and Smallest Array Elements
Arrays are useful for comparing values and finding the maximum or minimum element.
Example: Finding the largest value
#include <iostream>
using namespace std;
int main() {
int numbers[] = {25, 80, 15, 100, 45};
int largest = numbers[0];
for (int i = 1; i < 5; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
cout << "Largest: " << largest << endl;
return 0;
}Output:
Largest: 100Example: Finding the smallest value
#include <iostream>
using namespace std;
int main() {
int numbers[] = {25, 80, 15, 100, 45};
int smallest = numbers[0];
for (int i = 1; i < 5; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
cout << "Smallest: " << smallest << endl;
return 0;
}Output:
Smallest: 15Both examples assume the array contains at least one element.
12. Searching for an Element in an Array
You can search for a particular value by checking each element.
This method is called linear search.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int searchValue = 30;
int position = -1;
for (int i = 0; i < 5; i++) {
if (numbers[i] == searchValue) {
position = i;
break;
}
}
if (position != -1) {
cout << "Element found at index: " << position << endl;
} else {
cout << "Element not found" << endl;
}
return 0;
}Output:
Element found at index: 2Explanation
The program checks each element.
When it finds
30, it stores the index.breakstops the loop.The program prints the result.
Linear search works with both sorted and unsorted arrays.
13. Reversing an Array in C++
Reversing an array means changing the order of its elements so that the last element becomes the first.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = 5;
for (int i = 0; i < size / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[size - 1 - i];
numbers[size - 1 - i] = temp;
}
for (int value : numbers) {
cout << value << " ";
}
return 0;
}Output:
50 40 30 20 10The program swaps elements from opposite ends until it reaches the middle.
14. One-Dimensional Arrays in C++
A one-dimensional array stores elements in a single sequence.
Syntax
data_type array_name[size];Example
#include <iostream>
using namespace std;
int main() {
int marks[5] = {70, 80, 85, 90, 95};
for (int i = 0; i < 5; i++) {
cout << "Student " << i + 1
<< ": " << marks[i] << endl;
}
return 0;
}Output:
Student 1: 70
Student 2: 80
Student 3: 85
Student 4: 90
Student 5: 95One-dimensional arrays are useful for storing lists of marks, prices, ages, temperatures, and other related values.
15. Two-Dimensional Arrays in C++
A two-dimensional array stores values in rows and columns.
It is commonly used to represent tables and matrices.
Syntax
data_type array_name[rows][columns];Example
#include <iostream>
using namespace std;
int main() {
int numbers[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << numbers[i][j] << " ";
}
cout << endl;
}
return 0;
}Output:
10 20 30
40 50 60Explanation
The array contains two rows.
Each row contains three columns.
numbers[i][j]accesses an element using its row and column indexes.Nested loops traverse all elements.
16. Three-Dimensional Arrays in C++
A three-dimensional array stores elements using three indexes.
It can represent data arranged in layers, rows, and columns.
Syntax
data_type array_name[layers][rows][columns];Example
#include <iostream>
using namespace std;
int main() {
int numbers[2][2][2] = {
{
{10, 20},
{30, 40}
},
{
{50, 60},
{70, 80}
}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
cout << numbers[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}Output:
10 20
30 40
50 60
70 80Three-dimensional arrays are useful for certain scientific, mathematical, and simulation applications.
17. Character Arrays in C++
A character array stores individual characters.
Character arrays are sometimes used to represent C-style strings, which are terminated by the null character '\0'.
Example
#include <iostream>
using namespace std;
int main() {
char name[] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << name << endl;
return 0;
}Output:
HelloYou can also initialize a character array using a string literal.
char name[] = "Hello";The compiler includes the terminating null character.
For ordinary text processing in modern C++, std::string is usually easier and safer.
18. Arrays vs Vectors in C++
Built-in arrays and std::vector are both used to store multiple values, but they have different features.
A built-in array has a fixed size, while a vector can grow or shrink dynamically.
Comparison table
| Feature | Built-in array | std::vector |
|---|---|---|
| Size | Fixed | Dynamic |
| Declaration | int a[5] | vector<int> a |
| Memory management | Automatic for local arrays | Managed by the container |
| Adding elements | No direct resizing | push_back() |
| Removing elements | No direct resizing | pop_back() |
| Access | a[i] | a[i] or a.at(i) |
| Library support | Language feature | Standard library container |
Example using vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {10, 20, 30};
numbers.push_back(40);
for (int value : numbers) {
cout << value << " ";
}
return 0;
}Output:
10 20 30 40Use built-in arrays when a fixed-size array is appropriate. Prefer std::vector when the number of elements may change during program execution.
19. Common Mistakes When Working With Arrays
Beginners often make these mistakes when using arrays.
1. Accessing an invalid index
Incorrect:
int numbers[5] = {10, 20, 30, 40, 50};
// Invalid: index 5 is outside the array.
cout << numbers[5];Solution: For an array of five elements, use indexes from 0 to 4.
2. Forgetting that indexing starts at zero
The first element is numbers[0], not numbers[1].
3. Using an uninitialized local array
int numbers[5];The elements are not automatically initialized to zero in this declaration.
Solution: Initialize the array when creating it, or assign values before reading them.
4. Using the wrong array size
The declared size must match the number of elements you intend to store.
5. Assuming arrays can grow automatically
Built-in arrays have a fixed size.
Solution: Use std::vector when you need a resizable collection.
6. Forgetting array size when passing to functions
An ordinary array parameter is adjusted to a pointer, so the function does not automatically know the original array length.
Solution: Pass the size separately or use std::array or std::vector.
20. Best Practices for Using Arrays in C++
Follow these practices when working with arrays:
Use meaningful array names.
Initialize elements before reading them.
Always check valid array indexes.
Use loops to process multiple elements.
Use range-based
forloops when suitable.Use
constwhen array elements should not be modified.Prefer
std::arrayfor fixed-size collections when appropriate.Prefer
std::vectorfor dynamically sized collections.Avoid hard-coding array sizes in multiple places.
Test programs with empty, small, and large collections where applicable.
21. Frequently Asked Questions (FAQs)
Q1. What is an array in C++?
An array is a collection of elements of the same data type stored in a sequence and accessed using indexes.
Q2. How do you declare an array in C++?
Use the data type, array name, and size:
int numbers[5];Q3. How do you initialize an array?
You can assign values when declaring it:
int numbers[5] = {
10, 20, 30, 40, 50
}
;Q4. Does array indexing start from zero in C++?
Yes. The first element has index 0, the second has index 1, and so on.
Q5. How do you access an array element?
Use the array name followed by the element index:
cout << numbers[0];Q6. Can we update array elements?
Yes. Assign a new value to a valid index:
numbers[0] = 100;Q7. What is a multidimensional array?
A multidimensional array uses more than one index. A two-dimensional array, for example, stores elements in rows and columns.
Q8. What is the difference between an array and a vector?
A built-in array has a fixed size, while std::vector can change its size dynamically.
Q9. How do you find the length of an array?
For a built-in array in its original scope, use sizeof(array) / sizeof(array[0]), or use std::size() in C++17 and later.
Q10. Can an array store different data types?
A built-in array stores elements of one type. To store different types together, consider structures, classes, or suitable standard library types such as std::variant.
Runnable Code Example: Arrays in C++
C++20 / C++23#include <iostream>
#include <array>
int main() {
// Modern std::array
std::array<int, 5> scores = {92, 85, 78, 95, 88};
scores[0] = 96; // Direct indexing
std::cout << "Array Size: " << scores.size() << "
";
std::cout << "Elements: ";
for (int score : scores) {
std::cout << score << " ";
}
std::cout << "
";
// Safe bounds-checked access
try {
std::cout << "Element at index 2: " << scores.at(2) << "
";
// scores.at(10); // Throws std::out_of_range
} catch (const std::out_of_range& e) {
std::cerr << "Out of range error caught: " << e.what() << "
";
}
return 0;
}