How to Loop through an Array in C
Table of Contents
The benefits of arrays is that they can hold many different elements in a single variable.
To access all the elements, you'll need to iterate, or loop, through the array, gaining access to each element one by one.
In this post, we'll learn how to create an array and how to loop through it.
Looping through an array
Let's start with an example array:
CLIKEconst int length = 10;
int array[length] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
In our example, we first defined how big the array is going to be in the length
variable.
This is useful because in C, the length of the variable is not automatically kept track of for you like in other languages.
With that length, we then created an int
array with the same length, and populated it with the values 1 through 10.
Now let's try iterating over this array and print out each element:
CLIKEconst int length = 10;
int array[length] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < length; i++) {
printf("%d\n", array[i]);
}
BASH1
2
3
4
5
6
7
8
9
10
Conclusion
In this post, we created an int
array and iterated over it to print each element on a new line.
Thanks for reading and happy coding!
- Getting Started with Svelte
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Setting Up Stylus CSS Preprocessor