int nums[] = {10, 20, 30, 40, 50};
int size = sizeof(nums) / sizeof(nums[0]); // calculate size
for (int i = 0; i < size; i++) {
cout << nums[i] << " ";
}
// Output: 10 20 30 40 50
// Range-based for (cleaner)
for (int n : nums) {
cout << n << " ";
}
Multi-Dimensional Arrays
A 2D array is like a table of rows and columns:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
Output:
1 2 3
4 5 6
Note: C++ does not check array bounds. Accessing arr[10] on a 5-element array is undefined behavior. Use std::vector or std::array for safe alternatives.
Exercise
Declare an array of 5 temperatures. Find and print the highest and lowest values.
Show Solution
#include <iostream>
using namespace std;
int main() {
double temps[] = {36.5, 37.1, 38.0, 35.9, 37.5};
int n = sizeof(temps) / sizeof(temps[0]);
double highest = temps[0], lowest = temps[0];
for (int i = 1; i < n; i++) {
if (temps[i] > highest) highest = temps[i];
if (temps[i] < lowest) lowest = temps[i];
}
cout << "Highest: " << highest << endl;
cout << "Lowest: " << lowest << endl;
return 0;
}
Quiz
What is the index of the first element in a C++ array?
A) 1
B) -1
C) 0
D) It depends on the type
Answer
C) 0 — arrays are zero-indexed in C++.
How do you calculate the size of an array int arr[]?
A) arr.size()
B) sizeof(arr) / sizeof(arr[0])
C) len(arr)
D) arr.length()
Answer
B) For C-style arrays, sizeof(arr) / sizeof(arr[0]) gives the element count.
Summary
Arrays store multiple values of the same type, indexed from 0.
Declare: type name[size] = {values};
Use sizeof(arr)/sizeof(arr[0]) to get array length.