Previous topic |
Next topic |
Ada Home Page |
Index
For statement
In Ada, definite iteration is performed using a for statement
Statement form
for loop_var in index_type range low_val..high_val
loop
statement(s);
end loop;
Examples:
for i in INTEGER range -1 .. 10 loop
PUT(i);
NEW_LINE;
end loop;
for i in INTEGER range 1 .. 10 loop
PUT(i);
NEW_LINE;
end loop;
for i in INTEGER range 2 .. n-1 loop
PUT(i);
NEW_LINE;
end loop;
An example program
shows the use of a FOR statement to print a table of numbers and their
squares. The number of lines in the table is provided by the user, and so
is known at the time when the loop starts executing.
Another example
shows how the average number of items over 12 months can be computed, using
a FOR loop to process each month in turn.
Rules for for statements
- loop_var is a variable that is not previously declared, it
is implicitly declared in the loop, of type index_type, and is called
the loop parameter
- within the statement(s) inside the loop, the value of the loop
parameter may not be changed
- low_val and high_val may be variables, constants,
literals or expressions
- the loop executes at least once provided low_val <=
high_val, otherwise it never executes
- the statement(s) may be any Ada statements
- the entire for structure (from for to end loop) is a single
Ada statement, terminated by a ;
Style Rules for FOR statements
- statement(s) inside the for are indented by a constant amount
- the end loop is required, and should be at the same indent as the
corresponding for
Semantics of FOR statement
Sometimes need to count backwards. The
reverse variant of the for loop allows this.
for loop_var in reverse index_type range low_val .. high_val loop
statement(s);
end loop;
An example program
shows the use of a FOR statement to print a table converting miles per
hour to kilometers per hour, with the entries in reverse order.
Previous topic |
Next topic |
Ada Home Page |
Index
c-lokan@adfa.oz.au / 13 Feb 96