How to programmatically calculate the area of a cone in C#
Overview
The surface area of a cone is the summation of the curved area of the cone and the area of the base.
Where,
ris the radius of the cone.his the height of the cone.
πis the mathematical pi.
In C#, we can easily calculate the area of a cone. All we need to do is apply the formula or logic below.
Syntax
Math.PI * r * (r + Math.Sqrt(h*h + r*r));
Variables
Math.PI: This is the pi we know in mathematics.
r: This represents the radius of the cone.
h: This represents the height of the cone.
Return value
The value returned is a double value which represents the surface area of a cone.
Example
using System;class HelloWorld{// create function to get the areasstatic void GetArea(double h, double r){double area = Math.PI * r * (r + Math.Sqrt(h*h + r*r));Console.WriteLine("The area of the cone with height "+h+" and radius "+r+" is "+area);}// main methodstatic void Main(){// create some radii of some conesdouble r1 = 10;double r2 = 1.5;double r3 = 4.5;// create also the heights of each conedouble h1 = 2.2;double h2 = 5;double h3 = 20.5;// get the area of the conesGetArea(h1, r1);GetArea(h2, r2);GetArea(h3, r3);}}
Explanation
- Line 5: We create a method called
GetArea()that takes two parameters, height and radius. It calculates the area of the cone and tells the user the result in the console. - Lines 14–16: Within the main function, we define the radii of the cones we want to calculate the areas of.
- Lines 19–21: We define the heights of the cones as well.
- Lines 24–26: We invoke the
GetArea()method and passed it to the radii and heights we have created. We print the results to the console.