In C++, you can get the size of an array in several ways. The most common approach depends on whether you’re using a static array (i.e., an array with a fixed size).
Example:
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
// Get the size of the array
int size = sizeof(arr) / sizeof(arr[0]);
cout << "The size of the array is: " << size << endl;
return 0;
}
Explanation:
- sizeof(arr) gives the total size of the array in bytes, It has 5 element and every integer element has 4 bytes so total bytes = 5*4= 20.
- sizeof(arr[0]) gives the size of a single element of the array.
- Dividing sizeof(arr) by sizeof(arr[0]) gives the total number of elements in the array.
Output:
The size of the array is: 5
Use Array Size in for loop
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
for(int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) {
cout << "Array element: " << arr[i] << endl;
}
return 0;
}
Explanation:
- Array Declaration: int arr[] = {10, 20, 30, 40, 50}; creates an array with 5 elements.
- Array Size: sizeof(arr) / sizeof(arr[0]) calculates the number of elements in the array instead of direct pass value 5.
- Looping: A for loop is used to iterate through the array and print each element
Output:
Array element: 10
Array element: 20
Array element: 30
Array element: 40
Array element: 50
Array element: 20
Array element: 30
Array element: 40
Array element: 50