Greatest Common Divisor

This program finds the greatest common divisor of two numbers using Euclid's algorithm:

	/* gcd program */
	
	use(io). 
	
	gcd(a:val(int),b:val(int)):expr(int)=(
	  if (a>b)
	  then
	    gcd(a-b,b)
	  else if (b>a)
	  then
	    gcd(a,b-a)
	  else
	    a
	). 
	
	n1:var(int). 
	n2:var(int). 
	
	print("Greatest Common Divisor\n"); 
	print("Enter n1:\n");
	n1:=readint; 
	print("Enter n2:\n");
	n2:=readint; 
	print("The greatest common divisor is "); 
	print(gcd(n1,n2)); 
	print("\n")
Observe the following:

Compilation and Execution

Here's how to compile and execute the gcd example:

	ernie$ lcd gcd.l
	ernie$ li gcd.bcode
	Greatest Common Divisor
	Enter n1:
	? 216
	Enter n2:
	?723
	The greatest common divisor is 3
	Program terminated

	ernie$

Debugging

You can single step through your program using li's sourceview module. But to support this you need to compile with debugging enabled using lcd's -g flag:

	ernie$ lcd -g gcd.l
Enabling debugging slows execution so don't use -g when you don't need it. You can combine -g and -O without problems.

To run the debugger, type

	ernie$	li gcd.bcode sourceview
This will pop up several windows, two of which are interesting. This one is the "main" window for the program and is where gcd's input/output goes:

The other interesting one is the sourceview window which at this point is rather small:

The other windows can all be closed by choosing Window->Close on their menubars.

Clicking on "Step" in the sourceview window will cause the program to step to its first line and the sourceview will be updated to look like this:

The red 1> indicates the current line. 1 means thread one; this program has only one thread. The facilities available in the debugger are fairly limited - basically you have single stepping and breakpoints. Set a breakpoint by clicking on the line where you want to set the breakpoint, and choose Breakpoint->Add. An anchor symbol is displayed in the margin against the line that was selected.

When the program reaches a line requiring input a ? prompt is shown in the main window and the Run and Step buttons are disabled.

Once the program has finished it displays "Error: Program Terminated" in a dialog box. (The "Error:" bit may go away eventually). Having OKed this box it is in theory possible to reload the program using Simulatuion->Reload from the main menu, but this doesn't work too well so I suggest choosing Session->Quit and starting again.