A for loop is used to perform the same piece of code several times. Usually, this piece of code depends on some counter, which is also used to determine when the loop ends.
For example, suppose you have an array of numbers, A. You want to run through the whole array, and everytime you find an even number, you want to update it with zero. If the number is odd, you want to update it with one.
For example, the array A = [20, 13, -14, 2, 11] would become A = [0, 1, 0, 0, 1].
Now, you might write the checks for all positions (assuming that you know the lenght of the array beforehand!), like this:
if(A[0]%2==0) {A[0]=0;} else A[0]=1;
if(A[1]%2==0) {A[1]=0;} else A[1]=1;
if(A[2]%2==0) {A[2]=0;} else A[2]=1;
if(A[3]%2==0) {A[3]=0;} else A[3]=1;
if(A[4]%2==0) {A[4]=0;} else A[4]=1;
As you can see, there are a lot of repetitions, because we're basically asking the computer to perform the same operations and checks of each entry of the array.
A for loop is exactly what we need. Look at how clearer and simpler the code becomes:
for(i=0; i<5; i++){
if(A[i]%2==0) {A[i]=0;} else A[i]=1;
}
That's it! Let's take a look on how this works: the sketch of a for loop is
for([initial condition], [exit check], [action to perform after each step]){
[code to run with each step]
}
So, in our case, the initial condition is i=0. This variable i will be our counter, that will run from 0 to 4, so that we will span the whole array. The exit check is i<5. This means that we will stay inside the loop as long as this condition is true. In fact, we want to terminate the loop when i=5, because we couldn't access the sixth element of the array. Finally, after each step, we increase i by 1 (i++), so that we will point at the next element of the array, and we will perform the same operation on that element.