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}) ]

  1. Importing the I/O Package:

    With Gnat.IO; use Gnat.IO;
    
    • This imports Gnat.IO, allowing the use of Put (for output) and Get (for input).
  2. Declaring the Procedure:

    procedure perimeterofrectangle is
    
    • Defines the procedure named perimeterofrectangle.
  3. 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.
  4. 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 and height.
    • Reads the values into respective variables.
  5. Calculating the Perimeter:

    perimeter := 2 * (width + height);
    
    • Computes the perimeter using the formula 2 × (Width + Height).
  6. Displaying the Result:

    Put_Line ("Area = " & integer'image(perimeter));
    
    • Uses integer'image(perimeter) to convert the integer into a string.
    • Prints the calculated perimeter.
  7. 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