w3resource

C++ Exercises: Print the area and perimeter of a rectangle

C++ Basic: Exercise-40 with Solution

Write a C++ program to print the area and perimeter of a rectangle.

Visual Presentation:

C++ Exercises: Print the area and perimeter of a rectangle

Sample Solution:

C++ Code :

#include <iostream> // Including the input-output stream header file
using namespace std; // Using the standard namespace

int main() // Start of the main function
{
    float ar, peri, width, height = 0; // Declaration of variables for area, perimeter, width, and height with initialization
    cout << "\n\n Print the area and perimeter of a rectangle:\n"; // Outputting a message indicating the purpose of the program
    cout << "----------------------------------------------\n";
    cout << " Input the width of the rectangle: "; // Prompting the user to input the width of the rectangle
    cin >> width; // Taking user input for the width of the rectangle
    cout << " Input the height of the rectangle: "; // Prompting the user to input the height of the rectangle
    cin >> height; // Taking user input for the height of the rectangle

    peri = 2 * (width + height); // Calculating the perimeter of the rectangle
    ar = height * width; // Calculating the area of the rectangle

    cout << "The area of the rectangle is: " << ar << "\n"; // Outputting the calculated area of the rectangle
    cout << "The perimeter of the rectangle is: " << peri << "\n"; // Outputting the calculated perimeter of the rectangle
}

Sample Output:

  Print the area and perimeter of a rectangle:                          
----------------------------------------------                         
 Input the width of the rectangle: 8.5                                 
 Input the height of the rectangle: 5.6                                
The area of the rectangle is: 47.6                                     
The perimeter of the rectangle is: 28.2

Flowchart:

Flowchart: Print the area and perimeter of a rectangle

C++ Code Editor:

Previous: Write a program in C++ to print the specified pattern.
Next: Write a program in C++ to print an American flag on the screen.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/basic/cpp-basic-exercise-40.php