/

Looping through an array with C

Looping through an array with C

In this blog post, we will discuss how to loop through an array in the C programming language. Looping through an array is a common use case when working with arrays in C, and it allows us to perform operations on each element of the array.

Let’s consider the following array as an example:

1
2
const int SIZE = 5;
int prices[SIZE] = { 1, 2, 3, 4, 5 };

To iterate over each element of the array, we can use a for loop. Here’s an example:

1
2
3
for (int i = 0; i < SIZE; i++) {
printf("%d\n", prices[i]);
}

In this loop, we initialize a variable i to 0, which represents the index of the first element in the array. The loop continues as long as i is less than the size of the array (SIZE). After each iteration, we increment i by 1 using the i++ expression. Inside the loop, we can perform any operations we want on each element of the array. In this case, we are printing the value of each element using the printf function.

By looping through the array with this for loop, we can access and process each element of the array individually.

To summarize, looping through an array in C can be achieved by using a for loop, where we initialize a loop counter, set the loop condition to continue until the counter reaches the size of the array, and perform operations on each element inside the loop.

Tags: C programming, arrays, for loop