Definition of For (repetition structure in programming)

FOR is a repetition structure used in programming algorithms to repeat a code one or more times depending on a counter.

For allows you to control the execution flow of programming statements, allowing you to repeat a code.

FOR or DO

In general, programming languages ​​descending from ALGOL use the noun «for», but those descending from Fortran use the noun «do» to implement the same structure.

Meanwhile, in COBOL language «PERFORM VARYING» is used.

FOR operation

The For structure has an explicit counter, this allows the body of the For (the code that is executed repeatedly) to know in which repetition it is.

Generally, the For structure is used when the number of iterations required before entering the repetitions is known in advance.

A For can be constructed using a While with a counter and adding the «break» condition associated with the counter to the While.

The FOR was first used in ALGOL 58, a direct translation of the German fr used in Superplan (1949-1951) by Heinz Rutishauser, who was also involved in defining ALGOL 58 AND ALGOL 60.

Diagram of the flow of execution in a typical FOR structure

FOR example in C

Let’s see an example in C language:

int counter;

for (counter = 1; counter {
printf(Repeat number %d, counter);
};

First, the counter variable of integer type is created (to be the control variable in the for). The for structure is then executed, starting the counter variable at 1.

Then it is verified that the counter condition is met and the block within the structure is executed, that is, it prints the text Repetition number 1 on the screen.

Then the counter variable is incremented by one with the counter++ command and the loop starts again. The counter variable is now 2, so the condition is verified and the code is executed again.

This process is executed until the counter variable takes the number 11 and the condition becomes false, not executing the for block or body.

This code will print the following to the screen:

repetition number 1
repetition number 2
repetition number 3
repetition number 4
repetition number 5
repetition number 6
repetition number 7
repeat number 8
repeat number 9
repetition number 10

Breaking the FOR structure

Most programming languages ​​have some command or function that breaks the repetition of the For structure, regardless of whether it should continue to iterate. Usually the named functions exit or break are used.

Programming purists claim that these loop-breaking functions should not be included in the body of a For or While, because they obscure the programming code and sometimes make the loop itself meaningless.

related terminology

repeat structure

While

control structure

Doubts? needs more information? Write and we will respond to your email: click here