An Array is a collection of data items of the same type stored in contiguous memory locations. Instead of creating 50 separate variables for 50 students' marks, you create one array to hold them all.
1. Key Characteristics
Fixed Size: You must specify the size when you create the array, and it cannot be changed later.
Zero-Indexed: In C++, counting starts at 0. The first element is at index
0, the second at1, and so on.Homogeneous: All elements must be the same data type (e.g., all
intor alldouble).
2. Syntax
Declaration:
int marks[5];(Reserves space for 5 integers).Initialization:
int marks[5] = {90, 85, 70, 95, 80};Accessing:
marks[0]gives you90.
Code Example: Managing a Scoreboard
This program stores 5 scores in an array, updates one, and uses a for loop to calculate the average.
#include <iostream>
using namespace std;
int main() {
// 1. Declare and initialize an array
int scores[5] = {88, 76, 92, 45, 67};
// 2. Accessing and Modifying
cout << "Original first score: " << scores[0] << endl;
scores[3] = 50; // Changing the 4th element (index 3) from 45 to 50
// 3. Using a loop to process the array
int sum = 0;
cout << "All Scores: ";
for (int i = 0; i < 5; i++) {
cout << scores[i] << " ";
sum += scores[i]; // Adding each element to sum
}
// 4. Calculating Average
double average = (double)sum / 5;
cout << "\n\nTotal Sum: " << sum << endl;
cout << "Average Score: " << average << endl;
return 0;
}1. The 2D Array (Matrices)
A 2D array is the most common multi-dimensional type. It requires two indices to access an element: [row][column].
Syntax: int matrix[3][4]; // 3 rows and 4 columns (Total 12 elements).
2. Initialization & Access
You can visualize the initialization as a list of lists:
int grid[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};To get the number 6, you look at Row 1, Column 2: grid[1][2].
Code Example: A 3x3 Coordinate Grid
This program creates a 3x3 matrix, fills it with values, and uses nested loops (a loop inside a loop) to print it.
#include <iostream>
using namespace std;
int main() {
// 1. Declare and Initialize a 3x3 2D Array
int map[3][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
// 2. Accessing a specific element
cout << "Value at middle (Row 1, Col 1): " << map[1][1] << endl;
// 3. Printing the entire grid using Nested Loops
cout << "\n--- Full Grid ---" << endl;
for (int i = 0; i < 3; i++) { // Outer loop for Rows
for (int j = 0; j < 3; j++) { // Inner loop for Columns
cout << map[i][j] << "\t"; // \t adds a tab space
}
cout << endl; // New line after each row
}
return 0;
}3. Higher Dimensions (3D and Beyond)
You can go further: int cube[3][3][3];. Imagine this as 3 separate 2D grids stacked on top of each other. While C++ allows many dimensions, anything beyond 3D becomes very hard for humans to visualize and consumes massive amounts of memory quickly.