Referencing each element in an array definitely works, but it is inefficient because it takes up a lot of time and memory. There are other ways to go through, or iterate through, the array. A common way to iterate through arrays is by using a for loop. Let’s take a look at an example:
int nums[] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) { printf("%d\n", nums[i]); }
There is a lot going on in this code, but once you break it down, it’s quite simple. In the first line of code, we have declared and initialized our array called nums. Then, we have a for loop that will iterate through the array. How will it do this? Well, let’s break it down. First, a variable of type int named i is set to 0. Remember that i will be our counter, so to speak, in our for loop. Next, we have a conditional that checks to see if i is less than 5. The number 5 is significant here because it represents the size of our array. If you had an array that had a size of 10, your conditional would check to see if i is less than 10. There is no built-in method that allows you to retrieve the size of the array without knowing the explicit number, so you would need to know exactly how big your array is. Following the conditional, i is incremented by 1 after every iteration. Within the for loop, we are printing out the value of each element. We’re using the placeholder for an int variable within our printf statement because the data we are storing in our array is of type int. After the comma, however, is where things are a little different. Normally, we would type the name of the int variable that we want to print out. In this case, elements don’t have specific names, so to speak. Instead, we will reference each element by typing the name of the array, opening a pair of square brackets, inside of which we will use i. This will allow us to access and print out each element of the array. So, for the first iteration of the for loop, the printf statement would print out the value of nums[0], which is 1. In the second iteration, the printf statement would print out the value of nums[1], which is 2, and so on until the for loop stops running.
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.