# Kotlin Class: Triangle class with perimeter calculation

## Kotlin Class: Exercise-9 with Solution

Write a Kotlin program that creates a class 'Triangle' with side length properties. Include a function to calculate the triangle perimeter.

Sample Solution:

Kotlin Code:

``````class Triangle(
val side1: Double,
val side2: Double,
val side3: Double
) {
fun calculatePerimeter(): Double {
return side1 + side2 + side3
}
}

fun main() {
val triangle = Triangle(5.0, 6.0, 7.0)
val perimeter = triangle.calculatePerimeter()
println("Triangle Perimeter: \$perimeter")
}
```
```

Sample Output:

```Triangle Perimeter: 18.0
```

Explanation:

In the above exercise -

• First we define a class "Triangle" with three properties: side1, side2, and side3, representing the lengths of the triangle's sides.
• The class includes a function "calculatePerimeter()" that calculates the perimeter of the triangle by summing the lengths of all three sides.
• In the main() function, we create an instance of the Triangle class named triangle with side lengths 5.0, 6.0, and 7.0. We then call the "calculatePerimeter()" function on the triangle object and store the result in the perimeter variable.
• Using the println function, we print the perimeter calculated.

Kotlin Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿