Previous topic | Next topic | Ada Home Page | Index

General LOOP statement

The while loop tests for termination before executing the statements in the loop body.

Sometimes it is more natural to test part way through, or at end, of executing statements in the loop body.


	loop
		statements_1;
		exit when test;
		statements_2;
	end loop;

Semantics of General loop


Loop structures using the general LOOP statement

Exit at top

The while loop is the same as a general loop with an exit at the top

While:


	while  test  loop
		statements;
	end loop;

general:


	loop
		exit when not test;
		statements;
	end loop;

Exit in middle

When reading input till a particular value is entered, really want an algorithm like:

	   loop
		2. read a value from user
		3. if end value entered, leave the loop
		4. do something with value
	   end of loop

Another example is summing numbers up to (but excluding) an exit value:

while:

	PUT("Enter an integer (-1 to exit): "); 
	GET(j); SKIP_LINE;
	tot := 0;
	while j /= -1 loop
		tot := tot + j;
		PUT("Enter an integer (-1 to exit): "); 
		GET(j); SKIP_LINE;
	end loop;
	PUT("Total is "); PUT(tot); NEW_LINE;

general:


	tot := 0;
	loop
		PUT("Enter an integer (-1 to exit): "); 
		GET(j); SKIP_LINE;
		exit when (j = -1);
		tot := tot + j;
	end loop;
	PUT("Total is "); PUT(tot); NEW_LINE;

Note that statements need to be duplicated when using the while loop.

Exit at bottom

"post-test": test for termination after executing the loop body

	loop
		statement(s);
		exit when test;
	end loop;

Eg read until an acceptable value entered:

while:


	j := -1;
	while (j < 0) loop
		PUT("Enter positive integer: "); 
		GET(j); SKIP_LINE;
	end loop;

general:

		
	loop
		PUT("Enter positive integer: "); 
		GET(j); SKIP_LINE;
		exit when j >= 0;
	end loop;

The code in the general loop is easier to understand.


Previous topic | Next topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 13 Feb 96