For loop
For loop
Main page
2196071

For loop

logo
Community Hub0 subscribers
What are your thoughts?
Be the first to start a discussion here.
Be the first to start a discussion here.
For loop

In computer programming, a for loop is a structured control flow statement that repeatedly runs a section of code until a condition is satisfied.

A for loop has two parts: a header and a body. The header defines how the loop iterates, and the body is the code executed once per iteration. The header often declares a loop variable which can be used in the body to know which iteration of the loop is being executed. A relatively simple for loop iterates for a fixed number of times. For example, the following C for loop declares a loop variable i and prints its value as it increments from 0, 1, and 2:

Depending on programming language, various keywords are used to denote a for loop. For example, descendants of ALGOL use for, while descendants of Fortran use do and COBOL uses PERFORM VARYING.

Generally, a for loop falls into one of the following categories:

A numeric for loop increments a control variable from a start value to and end value. In languages such as ALGOL, Simula, BASIC, Pascal, Modula, Oberon, Ada, MATLAB, OCaml, and F# it looks like:

Some languages support an optional step value (increment or decrement). Some languages require a separate declaration of the control variable.

A 3-part for loop, popularized by C, has the following parts separated by semi-colons: initialization (loop variant), condition, and advancement to the next value. Each part is optional and can be blank. This syntax came from B programming language and was originally invented by Stephen C. Johnson. In the initialization part, any variables needed are declared and assigned values. The condition part checks a condition and exits the loop if false, even if the loop is never executed. If the condition is true, then the loop's block of is executed. The advancement to the next iteration part is performed each time the block is executed.

The following Java code is a C-style numeric loop that prints the numbers from 0 to 99.

See all
User Avatar
No comments yet.