Program to find the perimeter of a square given its area
Write a program to find the perimeter of a square given its area.
Examples:
Input: Area = 36 square units
Output: Perimeter = 24 units
Explanation: Since the area of the square is 36 square units, so the side of square will be 6 units. Therefore, the perimeter of the square will be 4 * 6 = 24 units.Input: Area = 25 square units
Output: Perimeter = 20 units
Explanation: Since the area of the square is 25 square units, so the side of square will be 5 units. Therefore, the perimeter of the square will be 4 * 5 = 20 units.
Approach: To solve the problem, follow the below idea:
The area of a square is given by Area=side×side. We can find the side length by taking the square root of the area. Once the side length is known, the perimeter can be calculated as Perimeter=4×side.
Step-by-step algorithm:
- Calculate the side length using the square root of the area.
- Calculate the perimeter using the formula Perimeter=4 × side.
- Print the calculated perimeter.
Below is the implementation of the algorithm:
C++
#include <cmath> #include <iostream> using namespace std; int main() { double area, side, perimeter; // Example Test Case area = 16; // Calculate side length side = sqrt (area); // Calculate perimeter perimeter = 4 * side; // Display result cout << "Perimeter: " << perimeter << endl; return 0; } |
C
#include <math.h> #include <stdio.h> int main() { double area, side, perimeter; // Example Test Case area = 16; // Calculate side length side = sqrt (area); // Calculate perimeter perimeter = 4 * side; // Display result printf ( "Perimeter: %.2f\n" , perimeter); return 0; } |
Java
import java.util.Scanner; public class SquarePerimeter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double area, side, perimeter; // Example Test Case area = 16 ; // Calculate side length side = Math.sqrt(area); // Calculate perimeter perimeter = 4 * side; // Display result System.out.println( "Perimeter: " + perimeter); } } |
Python3
import math # Example Test Case area = 16 # Calculate side length side = math.sqrt(area) # Calculate perimeter perimeter = 4 * side # Display result print (f "Perimeter: {perimeter}" ) |
C#
using System; class Program { static void Main() { double area, side, perimeter; // Example Test Case area = 16; // Calculate side length side = Math.Sqrt(area); // Calculate perimeter perimeter = 4 * side; // Display result Console.WriteLine( "Perimeter: " + perimeter); } } |
Javascript
// Example Test Case let area = 16; // Calculate side length let side = Math.sqrt(area); // Calculate perimeter let perimeter = 4 * side; // Display result console.log(`Perimeter: ${perimeter}`); |
Perimeter: 16
Time Complexity: O(log N), because it takes O(logN) time to calculate the square root of N.
Auxiliary Space: O(1)
Contact Us