After declaring an array, you will want to store data in your array at some point. Saving data to your array is more commonly referred to as initializing your array. Let’s look at the different ways to initialize your array:
- Initialization with Declaration
One of the most common ways to initialize the array is to do it on the same line that you declare the array. Here is what that would look like:
int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
In the above example, we take the same code we used to declare the array, except we got rid of the number between the brackets representing the size, because we don’t need to specify the size since the computer has the ability to count the number of elements we typed within the curly braces. After that, we used the equals sign, which is the assignment operator, to assign our data to the array. Next, we opened a pair of curly braces, within which I typed the numbers that I wanted to store within the array. Each element is separated by a comma. Then, at the end, you would close off with a semicolon.
- Initialization of Separate Elements
If you do not know what data you want to store in your array at the time of declaration, you can always initialize the array later. If you do this, you would have to initialize each value of the array separately as shown below:
int nums[5]; //declaration of array nums[0] = 1; nums[1] = 2; nums[2] = 3; nums[3] = 4; nums[4] = 5;
The first line of code above is the declaration of the array. After that, we initialized each element of the array separately. Remember that using 0 as an index would reference the very first element of the array. So, nums[0] represents the first element of the array. We use the assignment operator to assign the numbers 1 through 5 to each of the 5 elements of my array, separately.
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.