Program to calculate the length of the diagonal in a rectangle
Last Updated :
18 Jan, 2024
Write a program to calculate the length of the diagonal in a rectangle with the given length and breadth.
Examples:
Input: Length = 5, Width = 3
Output: Diagonal Length = 5.83095
Input: Length = 8, Width = 6
Output: Diagonal Length = 10
Approach: To solve the problem, follow the below idea:
The diagonal of a rectangle forms a right-angled triangle with the length and width of the rectangle. We can use the Pythagoras theorem to calculate the length of the diagonal. So, we can use this formula Diagonal2 = Length2 + Breadth2 to calculate the length of the diagonal.
Step-by-step algorithm:
- Square the length and width.
- Sum the squares.
- Take the square root of the sum.
Below is the implementation of the algorithm:
C++
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
double L = 5, W = 3;
double diagonal = sqrt (L * L + W * W);
cout << "Diagonal Length: " << diagonal << endl;
return 0;
}
|
C
#include <math.h>
#include <stdio.h>
int main()
{
double L = 5, W = 3;
double diagonal = sqrt (L * L + W * W);
printf ( "Diagonal Length: %lf\n" , diagonal);
return 0;
}
|
Java
public class DiagonalLength {
public static void main(String[] args)
{
double L = 5 , W = 3 ;
double diagonal
= Math.sqrt(Math.pow(L, 2 ) + Math.pow(W, 2 ));
System.out.println( "Diagonal Length: " + diagonal);
}
}
|
Python3
import math
L, W = 5 , 3
diagonal = math.sqrt(L * * 2 + W * * 2 )
print (f "Diagonal Length: {diagonal}" )
|
C#
using System;
class Program {
static void Main()
{
double L = 5, W = 3;
double diagonal
= Math.Sqrt(Math.Pow(L, 2) + Math.Pow(W, 2));
Console.WriteLine( "Diagonal Length: " + diagonal);
}
}
|
Javascript
let L = 5, W = 3;
let diagonal = Math.sqrt(L ** 2 + W ** 2);
console.log( "Diagonal Length: " + diagonal);
|
Output
Diagonal Length: 5.83095
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...