GoConqr has a new look! Let us know what you think.

Module 12 of 18 · Media

For Loop Syntax

Kostas Diakogiannis

For Loop Syntax

The For loop

The for loop is another type of loop exactly like while. In fact logic-wise the difference is non-existent. For is used exactly for the same purpose as while, the only thing that changes is the syntax as the image above shows.

So instead of defining the decisive variable outside the loop, we do it inside the condition, by splitting the parenthesis section into three areas.

Inside the first area we define the start of the decisive variable, at second position comes the condition we check after every iteration and last we define how we update the variable's value after iteration has finished.

This may seems to be a little bit harder at the beginning but leaves the body of the loop cleaner to put only the repeated code there.

Attention: For loops are a preferable option when we know exactly the number of iterations from before (thus is the best option when working with numbers). 

It is a good practice to use while loop when we don't know exactly the number of iterations from before.

Besides that, there is no significance difference between for and while and all the principles that we have learned in a while loop can also be applied in a for loop. (like the 'break' and 'continue' keyword).

Instructions

You must submit an attempt for this quiz to progress. You can submit it after the last question.

Go to the chosen module

Feedback

What is it about?

What do you think of the new look?

How do you like it?