Learn ADA-SPARK with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
1
Hello World in SPARK Ada
with Ada.Text_IO;
procedure Hello is
begin
Ada.Text_IO.Put_Line("Hello, World from SPARK Ada!");
end Hello;
A minimal SPARK Ada program that outputs 'Hello, World!'.
2
Safe Division with Contracts
function Safe_Divide(X, Y : Integer) return Integer
with Pre => Y /= 0,
Post => Safe_Divide'Result * Y = X is
begin
return X / Y;
end Safe_Divide;
A SPARK function that safely divides two numbers, using contracts to ensure correctness.
3
Sum of Two Numbers
with Ada.Text_IO;
procedure Sum_Numbers is
A, B, C : Integer;
begin
A := 5;
B := 7;
C := A + B;
Ada.Text_IO.Put_Line("Sum = " & Integer'Image(C));
end Sum_Numbers;
A SPARK Ada program adding two numbers and printing the result.
4
Factorial Function
function Factorial(N : Natural) return Natural is
begin
if N = 0 then
return 1;
else
return N * Factorial(N - 1);
end if;
end Factorial;
A recursive SPARK Ada function to compute factorial of a number.
5
Check Even Number
function Is_Even(X : Integer) return Boolean is
begin
return X mod 2 = 0;
end Is_Even;
A SPARK Ada function that returns True if a number is even.
6
Array Sum
function Array_Sum(Arr : array (Positive range <>) of Integer) return Integer is
Sum : Integer := 0;
begin
for I in Arr'Range loop
Sum := Sum + Arr(I);
end loop;
return Sum;
end Array_Sum;
A SPARK Ada function that sums all elements of an integer array.
7
Max of Two Numbers
function Max(X, Y : Integer) return Integer is
begin
if X >= Y then
return X;
else
return Y;
end if;
end Max;
A SPARK Ada function returning the maximum of two integers.
8
Swap Two Numbers
procedure Swap(A, B : in out Integer) is
Temp : Integer;
begin
Temp := A;
A := B;
B := Temp;
end Swap;
A SPARK Ada procedure that swaps the values of two integers using in-out parameters.
9
Simple Loop Print
with Ada.Text_IO;
procedure Loop_Print is
begin
for I in 1 .. 5 loop
Ada.Text_IO.Put_Line(Integer'Image(I));
end loop;
end Loop_Print;
A SPARK Ada program that prints numbers from 1 to 5 using a loop.
10
Check Prime Number
function Is_Prime(N : Natural) return Boolean is
begin
if N <= 1 then
return False;
end if;
for I in 2 .. N - 1 loop
if N mod I = 0 then
return False;
end if;
end loop;
return True;
end Is_Prime;
A SPARK Ada function that checks if a number is prime.