Unlike while and do…while, for loops allow you to repeat a set of instructions for a specific number of times in a more efficient way.

Last week I started talking about loops in C and I showed you how while and do…while work.

This time instead we’re going to examine for and keywords, such as break, continue and goto.

FOR

First things first, for what do we use for? Why is it different from while?

For is used to repeat a set of instructions a specific number of times. On the other hand, the number of times a while loop is repeated isn’t certain, because it depends on a condition that can be influenced by the user.

Of course, both for and while can do the job of the other, but they’re particularly efficient when they do their own.

If after the previous post you’ve tried to do some program on your own – thing that I highly recommend – you might have written something like this:

But you can get the same result in a simpler way:

And you can even shrink it more – I’ll tell you how in the “Tips and Tricks” section below.
In both cases you’ll get this result:

Output for vs while

Nevertheless, for has a more strange syntax compared to all the flow statements we’ve seen so far – if, else, else if, while, do…while.

Syntax

Let’s have a look at it:

There’s a bunch of things here to explain:

  1. initialisation: here we can define a new variable or set the value of one already created;
  2. condition: it works just like the conditions for while and if;
  3. operation: the operation you want to execute at the end of each cycle, before the loop starts all over again.

Usually all three of these inputs uses the same variable, that is called counter and usually named i (=index).

In the flowchart below you can clearly see how a for loop works:

For loop flowchart

When a computer has to execute a for loop, it starts from initialising the variable. This action is done once at the beginning of the loop.

It won’t be repeated.

Then the machine tests the condition. This happens at the beginning of each cycle. If the result is true ( or a number different from 0 ), the computer will run the code inside for. Otherwise it will quit it.

The final phase of a for loop is the operation. It’s executed at the end of each cycle, before testing the condition again.

How do all these work together?

Initialisation

Usually we use for to repeat a sequence of instructions for a specific amount of times and to do that we use a special variable, called counter.

It isn’t special because it has some sort of extra property, but because of its function.

In fact it keeps count of how many cycles are executed, so we also call it index and we abbreviate it to i in programs.

Condition

We declare that variable in our for statement and set a condition using it as one of the two parameters.

We usually test if it’s less that a number, that is the number of times the loop will repeat.

Now I must explain something that few people get when they use this statement for the first time.

If you want to repeat a set of instructions for 4 times, you have to use the condition i not i if you initialise i to 0.

Remember that the computer execute the operation at the end of the cycle, not before testing the condition.

So, in this case:

There'll be 6 outputs: 0, 1, 2, 3, 4, 5.

For condition with equal

While in this case:

There'll be 5 outputs: 0, 1, 2, 3, 4.

For output without equal

You should start getting used to counting from zero instead of one, because C - and other programming languages - do so. It'll be very important when we will study arrays.

If you want to write in a way more similar to human way of thinking, initialise the variable to 1 and use less-than or equal.

Operation

Finally, to make the computer count the cycles, we increment the variable i by 1.

To do that you can use i=i+1 or i++, which is "shortcut". There's also another operation that do the same thing and it is ++i.

I've discovered this last one only recently - there's always room for improvements - and it differs from i++.

I think it's easier to explain with an example. Let's say b = 2:

  • a = b++; The result is a=2 and b=3. The increment is done after the operation.
  • a = ++b; The result is a=3 and b=3. The increment is done before the operation.

In for nothing changes between the two.

I highly recommend you this post by embedded.com - Pre-increment or post-increment in C/C++ - if you more information on this topic.

 

Control statements

What is a control statement?

It's a keyword that changes the normal flow of a program.

There are three control statements in C: break, continue and goto.

Break

break example

We met the break statement when we learnt about switch.

The break keyword makes the computer quit the current scope - which can be if, while, for and so on and so forth - without completing it.

It ignores any condition of the statement - as well as all others do.

Continue

continue example

It's very similar to break, but instead of quitting the entire loop, it just jump to the next cycle.

In while, it makes skip the conditional test.

In for, both the conditional test and operation are executed.

Goto

goto example

Goto - that stands for "go to" - forces the program to jump to a specific statement.

To do that you label the arrival point with label: and you call goto followed by that name.

Don't use it at work or school, because it isn't recommended, since it makes hard to understand the code, so to modify it.

Tips and tricks

  1. You can also not use the curly brackets if your loop contains only one statement.
  2. Not always you can define a variable inside for's brackets. Old compilers, such as the one that Dev-C++ uses, don't support this feature.

Let's analyse the for loop in today's program

Since we want the program to print the times table of a number, each cycle of the loop has to multiply that number by an increasing one, that I called i.

The program meets for and it create the variable i with an initial value of 0. Then it test the condition - is i less than 13? - and enters the loop.

There'll be 13 cycles and for each of the computer will multiply the the user's number  n by the increasing value of i and print it.

So we will get:

To print the result I used printf in a way that seems quite complex.

There are three %d, which - as you know because you've read all my posts - mark three integer numbers: the multiplicand, the multiplier and the result.

There are also four \t. It's a special character that tell the computer to move the cursor to the next tab stop - usually four normal spaces. It's used to organise the words on the console in a table-like format.

Finally, there's a \n that we've met thousand of times so far and it means "go to a new line".

One last note: I wrote the multiplication inside printf, in fact you can use operations as function parameters.

Code's translation

This program uses the Standard IO library

Here's the main body of the program

Print "Enter a number: "

Create an integer variable called n

Read an input from the console and assign its value to n

Move the cursor to the next tab stop, print the value of n and then times table. Go to a new line twice.

Repeat this loop twelve times and increment the value of i each time:

Print n, go to the next tab stop, print "x", next tab stop, print n, next tab stop, print "=", next tab stop, print the result of n times i, then go to a new line.

Conclusion

What is for? When should I use it? How do I use it?

For is one of the hardest statements to understand for a beginner. Its parameters are separated by semicolons, not commas, and this can be quite confusing, without taking into account that each of them is considered in different parts of the cycle or just once for the entire loop.

However, now you know all of this, so congratulation, because you're about to learn the best part of C programming, but that is a topic for the next time.

Keep in touch!

Write a comment about how bad I'm at teaching or how useful this guide was for you!

Jokes aside, if there's anything you haven't understood, write me about it and I'll happily answer you.

Share this with your friends, if they want to learn programming with you - you find the sharing buttons below.

Anyway, the post is finished, have a good day and we will see next week!

From Zephyro it’s all, Bye!


Leave a Reply

%d bloggers like this: