ADA Program to find perimeter of rectangle
Program
With Gnat.IO; use Gnat.IO;
procedure perimeterofrectangle is
width : Integer;
height: Integer;
perimeter : Integer;
begin
Put ("Enter the width of the rectangle: ");
Get (width);
Put ("Enter the height of the rectangle: ");
Get (height);
perimeter := 2 * (width + height);
Put_Line ("Area = " & integer'image(perimeter));
end;
This Ada program calculates the perimeter of a rectangle based on user input for width and height using the formula:
[ \text{Perimeter} = 2 \times (\text{Width} + \text{Height}) ]
-
Importing the I/O Package:
With Gnat.IO; use Gnat.IO;
- This imports
Gnat.IO
, allowing the use ofPut
(for output) andGet
(for input).
- This imports
-
Declaring the Procedure:
procedure perimeterofrectangle is
- Defines the procedure named
perimeterofrectangle
.
- Defines the procedure named
-
Variable Declarations:
width : Integer; height: Integer; perimeter : Integer;
width
: Stores the width of the rectangle.height
: Stores the height of the rectangle.perimeter
: Stores the calculated perimeter.
-
Taking User Input:
Put ("Enter the width of the rectangle: "); Get (width); Put ("Enter the height of the rectangle: "); Get (height);
- Prompts the user to enter values for
width
andheight
. - Reads the values into respective variables.
- Prompts the user to enter values for
-
Calculating the Perimeter:
perimeter := 2 * (width + height);
- Computes the perimeter using the formula 2 × (Width + Height).
-
Displaying the Result:
Put_Line ("Area = " & integer'image(perimeter));
- Uses
integer'image(perimeter)
to convert the integer into a string. - Prints the calculated perimeter.
- Uses
-
End of the Procedure:
end;
- Marks the end of the procedure.
Key Takeaways:
- This Ada program calculates the perimeter of a rectangle using the formula 2 × (Width + Height).
- Uses Gnat.IO for user input and output.
- Can be improved by fixing the output message, handling negative values, and supporting floating-point numbers.
Output
$ gnat make perimeterofrectangle.adb
gcc -c perimeterofrectangle.adb
gnatbind -x perimeterofrectangle.ali
gnatlink perimeterofrectangle.ali
$ ./perimeterofrectangle
Enter the width of the rectangle: 21
Enter the height of the rectangle: 13
Area = 68