![]() |
Given the length of one side, our task is to find the perimeter of a square in JavaScript. The perimeter of a square is the total length of its four sides. It can be calculated by multiplying the length of one side by 4 and all its angles measure 90 degrees. Example: Formula for calculating Perimeter of Square is: 4*s Where, s is sides of a square Input: 4 Output: 16 Use the below approaches to find the Perimeter of the Square: Table of Content Using FunctionIn this approach, We will create a function that takes one parameter, the side of the square. Inside the function, calculate the perimeter of the square by multiplying the side length by 4 (as all sides of the square are equal). Return the calculated perimeter value. Example: The example below shows the demonstration of finding the perimeter of the square using the function
Output Perimeter of square is : 16 Time complexity: O(1) Space complexity: O(1) Using ClassIn this approach, define a class named Square. Within the class, a constructor method is defined to initialize the side length of the square. Additionally, a method is defined to calculate the perimeter of the square using the formula 4 * side. To utilize this class, an instance of Square is created by passing the side length as an argument to the constructor. Finally, the method for calculating the perimeter is called on the instance, and the result is printed. Example: The example below shows the demonstration of finding perimeter of square using class.
Output Perimeter of square is : 16 Time Complexity: O(1) Space Complexity: O(1) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |