next up previous
Next: Summary Up: The if-else Statement Previous: Example Program: Pythagorean Triples

Example Program: Area and Perimeter of Rectangle

Exercise 2 of Lesson 5 required an algorithm which given two values for the breadth and height of a rectangle would output the area and perimeter of the rectangle. However depending on whether the breadth and height were equal or not different messages would be output indicating whether it was a rectangle or a square. A suitable algorithm for this would be

enter values for breadth and height.
evaluate perimeter.
evaluate area.
if breadth is equal to height
    then
        output 'area and perimeter of square are '
    otherwise
        output 'area and perimeter of rectangle are'.
output area and perimeter.
This algorithm is then easily converted into a C++ program as follows:
// IEA 1996
// Calculates area and perimeter of a rectangle
// after input of breadth and height. Distinguishes
// a square from a rectangle.

#include <iostream.h>

void main()
{
  int breadth, height; // of rectangle
  int perimeter, area; // of rectangle
    // input breadth and height
  cout << "Enter breadth and height: ";
  cin >> breadth >> height;
    // calculate perimeter and area
  perimeter = 2*(breadth+height);
  area = breadth*height;
  if (breadth == height)
    cout << "Area and perimeter of square are ";
  else
    cout << "Area and perimeter of rectangle are ";
   // output area and perimeter
  cout << area << " " << perimeter
       << endl;
}
Download program.
Note how portions of the algorithmic description have been used as comments within the program. Remember that successive values sent to the output stream cout will each be printed immediately after the previous output value. Hence in the program above the printing of the actual values for the area and perimeter will be printed directly after the information string on the same line. If a new line is required then send the end of line marker endl to cout.


next up previous
Next: Summary Up: The if-else Statement Previous: Example Program: Pythagorean Triples
Peter JB King
1999-08-31