C-style arrays
- C++ course
- Beginner
- Lesson 53/116
- 4 min
Learn to declare C-style arrays with int[] and double[].
C-style arrays
The classic way to declare a fixed-size array in C++ is a C-style array. Its form is int nums[5] = {1, 2, 3, 4, 5};; the size goes inside square brackets and the initial values inside braces.
The size of the array is known at compile time and cannot change later. Indices are zero-based: nums[0] is the first element and nums[4] is the last element of a five-element array. C-style arrays are fast but do not check bounds automatically; that is why std::array is preferred at advanced levels.
Array size
The size of a C-style array is written inside the square brackets and fixed at compile time. int nums[5] reserves space in memory for five int values; this space cannot grow later.
If you write only int nums[5]; without initial values the elements contain garbage. Providing {0} in braces zeroes every element. Giving more values than the size yields a compile error.
Practice Declare the array and print the first element
Declare a five-element array as int nums[5] = {10, 20, 30, 40, 50}; and print the first element with std::cout << nums[0];. The output must be 10.
Starter code
#include <iostream>
int main() {
// Declare the nums array and print the first element
return 0;
}Sample solution
#include <iostream>
int main() {
int nums[5] = {10, 20, 30, 40, 50};
std::cout << nums[0] << std::endl;
return 0;
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For int nums[5] = {1,2,3,4,5}; what is nums[0]?
int nums[5] = {1,2,3,4,5};
nums[0]- 0
- 1 Correct answer
- 4
- 5
Explanation: Index 0 gives the first element; the value is 1.
2 Write the array name
int ____[5] = {1, 2, 3, 4, 5};
int nums[5] = {1, 2, 3, 4, 5};
Explanation: The array name is nums; C++ variable names are usually plural for arrays.
3 Match each array part to its role
| Term | Meaning |
|---|---|
int |
Type |
nums |
Array name |
[5] |
Size |
{1,2,3,4,5} |
Initial values |