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.83095Input: 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:
#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;
}
#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;
}
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);
}
}
import math
L, W = 5, 3
diagonal = math.sqrt(L**2 + W**2)
print(f"Diagonal Length: {diagonal}")
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);
}
}
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)