C++ program to calculate the area, perimeter and diagonal of a square has been given below. If length of the side of a square is $s~ unit$, the area, perimeter and diagonal of that square would be $s^2~\text{unit}^2$, $4s~\text{unit}$ and $s\sqrt{2}~\text{unit}$ respectively.
For example, if length of the side of a square is $5~cm$, the area would be $5^2 = 25~\text{cm}^2$ while the perimeter would be $4 \cdot 5 = 20~\text{cm}$. The diagonal will be calculated as $5\cdot \sqrt{2} = 7.071 ~\text{cm}$
In the following section, the algorithm, pseudocode and time-complexity of the program have also been covered.
1. Algorithm to calculate the area, perimeter and diagonal of a square
1. Take the length of side $s$ as input.
2. Declare $s^2$ as the area of the square
3. Declare $4s$ as the perimeter of the square
4. Declare $s\sqrt{2}$ as the diagonal of the square
2. Pseudocode to calculate the area, perimeter and diagonal of a square
Input : Length of side $s$
Output : Area $A$, Perimeter $P$ and Diagonal $D$ of the square
1. Procedure areaPerimeterDiagonal($s$):
2.
3.
4.
5.
6. End Procedure
3. Time complexity to calculate the area, perimeter and diagonal of a square
Time Complexity: O(1)
4. C++ Program to calculate the area, perimeter and diagonal of a square
/*********************************** alphabetacoder.com C++ program to calculate the area ,perimeter and diagonal of a square ************************************/ #include <iostream> #include <cmath> using namespace std; int main() { // declare variables float s, a, p, d; // take input cout << "Enter the length of side of the square: "; cin >> s; // calculate area a = s * s; // calculate perimeter p = 4 * s; // calculate diagonal d = s * sqrt(2); // display result cout << "Area: " << a << endl; cout << "Perimeter: " << p << endl; cout << "Diagonal: " << d << endl; return 0; }
Output
Enter the length of side of the square: 10.5
Area: 110.25
Perimeter: 42
Diagonal: 14.8492