In order to execute a block of code over an over again, loops comes into the picture. The for
loop is to be used when a block of code is to executed a fixed number of times.
For example, in order to fill an array of size n
with the user inputs, we need to execute scanf()
for n
times.
#include <stddef.h> // for size_t
int array[10]; // array of 10 int
for (size_t i = 0; i < 10; i++) // i starts at 0 and finishes with 9
{
scanf("%d", &array[i]);
}
In this way the scanf()
function call is executed n
times (10 times in our example), but is written only once.
Here, the variable i
is the loop index, and it is best declared as presented. The type size_t
(size type) should be used for everything that counts or loops through data objects.
This way of declaring variables inside the for
is only available for compilers that have been updated to the C99 standard. If for some reason you are still stuck with an older compiler you can declare the loop index before the for
loop:
#include <stddef.h> /* for size_t */
size_t i;
int array[10]; /* array of 10 int */
for (i = 0; i < 10; i++) /* i starts at 0 and finishes at 9 */
{
scanf("%d", &array[i]);
}