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

Style Rules for FOR statements

Semantics of FOR statement


Counting down in FOR statements

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