Previous topic | Next topic | Ada Home Page | Index

Loop control

There are three aspects to loop control for any loop:
  1. initialisation of loop parameter(s)
  2. test
  3. update loop parameter

Loop Design

Choose the appropriate loop statement, and then specify the three aspects to loop control.

Approaches to loop design:


Sentinel-controlled loops

When an unknown number of data items are to be processed, some way to recognise the end of the data is needed.

One solution is to define a sentinel value

Code template:


	sentinel : constant := ???;	

	loop
		read (item);
		exit when item = sentinel;

		process the item;

	end loop;

Example: add integers that the user enters, up to but not including -1 for end of data


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

Flag-controlled loops

A flag is a boolean variable, used to indicate whether or not a desired situation has occurred

Code template:


	flag : BOOLEAN;

	flag := FALSE;
	while not flag loop

		do some processing;

		if desired event has happened then
			flag := TRUE;
		end if;

		do some processing;

	end loop;

Example: read characters until a digit is typed


	DigitRead := FALSE;
	while not DigitRead loop
		get (c);
		if (c >= '0') and (c <= '9') then
			DigitRead := TRUE;
		end if;
	end loop;
			


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