In the first part of the article, we examined and explained the code inside
the loop codeblock as shown below:
/* Getting old
Written by VerticalE */
int myAge = 8;
for(int i = 0 ; i<10 ; i = i + 1)
{
prinf("My age is %d\n", myAge");
myAge++;
} |
Now we're gonna take a look at the really scary stuff outside of it.
We'll start with the following declaration:
int myAge = 8;
As you probarbly know, we are declaring an integer value with the name myAge
and assigning it the value 8 (to satisfy our younger readers). Next, we set
up out loop. In this case, we are using a for-loop. Their setup can
basically be divided into three sections, each separated with a semicolon.
|
for(
int i = 0
;
i<10
;
i = i + 1
) |
<- starting a for-loop
<-- part 1
<-- separator
<-- part 2
<-- separator
<-- part 3
<-- end of the for-loop setup |
Part 1
Here we are setting up the "counter". Just think about it; you cannot count
unless you use a number. Even when you count out loud with your voice, you
are in a way using a type of value that you are either incrementing or
decrementing. In our loop we call the counter variable "i", say that its an
integer value and set it at a starting value of 0. When we have told the
for-loop what variable we want to increment, we move on to the next part
with the semicolon as a separator.
Part 2
This part tells the for-loop how long it will loop. In this case, it will
loop for as long as the value of i is smaller than 10. Here are a few other
examples of what could be written in this part:
i>10 - i is bigger than 10 - would cause the application to just jump over
the whole loop, since i is never more than 10.
i!=10 - i is not 10 - would cause the loop to go on and on as long as i is
not 10. Would have the same impact as i<10.
i==10 - i is 10 - the loop wouldnt run at all, and the application would
just jump over the whole codeblock, disregarding it. Again, we separate this
part from the next with a semicolon.
Part 3
Here we increment the value (add 1) each time the loop runs. This means that
when the codeblock has been run once, the value is incremented - NOT before
it has run. Hence, the value of i the first time the loop runs is still 0,
until it has finished once, and start again. If you remember from the first
part of this article, we shortened the code down to a smaller statement.
This can be done here as well, using the ++ incremention operator. This
time, we dont need to end this statement with a semicolon, since it is the
last part of the for-loop setup. Our updated code now looks like this:
/* Getting old
Written by VerticalE */
int myAge = 8;
for(int i = 0 ; i<10 ; i++)
{
prinf("My age is %d\n", myAge");
myAge++;
} |
In the next part of this article series, will look at a new type of loop;
the while-loop. |