Loop

From LQWiki
Jump to navigation Jump to search

A loop manages control flow in a program, by executing a block of code a certain number of times.

A loop is used to implement iteration. Bounded iteration is the case where the number of iterations through the block is known before the loop begins. A for loop is a common case of bounded iteration. Unbounded iteration is used when the number of iterations is not known ahead of time, perhaps when performing an action on every line of a file whose size is unknown. A while or until loop is a common example of unbounded iteration.

For example; this Perl fragment uses unbounded iteration to process every line of input. Comments starting with '#' are discarded, and other lines are converted to lowercase and output.

while (<>) {
        next if /^\s*#/;
        print lc($_);
}

See also