Wednesday, April 30, 2025

C Program - Calculate Area of an Equilateral Triangle

This program calculates the area and perimeter of an equilateral triangle, given its side length. It prompts the user to enter the side length of the triangle, reads in the value using scanf, and then calculates the area and perimeter.

//Equilateral Triangle Area:

#include <stdio.h>
#include <math.h> // for sqrt() function

int main()
{

    float side, area, parimeter, temp_var;

    printf("Triangle Side: \n");
    scanf("%f", &side);

    temp_var = (sqrt(3) / 4);

    area = temp_var * side * side;
    printf("Area of Triangle: %f \n", area);

    parimeter = 3 * side;
    printf("Parimeter: %f \n", parimeter);

    return 0;
}

Result: 

Triangle Side:
20
Area of Triangle: 173.205078
Parimeter: 60.000000

Process returned 0 (0x0)   execution time : 2.818 s
Press any key to continue.

Here's a line-by-line explanation of the code: 

#include <stdio.h>
#include <math.h> // for sqrt() function

These are header files. The first one includes the standard input/output functions in C and the second one includes the math library which has the sqrt() function. 

int main()
{
    float side, area, parimeter, temp_var;

    printf("Triangle Side: \n");
    scanf("%f", &side);

This declares the main function and initializes some variables to hold the side length, area, perimeter, and a temporary variable. The program then prompts the user to enter the side length of the equilateral triangle and reads the value into the "side" variable using the scanf() function. 

    temp_var = (sqrt(3) / 4);

    area = temp_var * side * side;
    printf("Area of Triangle: %f \n", area);

    parimeter = 3 * side;
    printf("Parimeter: %f \n", parimeter);

    return 0;
}

This calculates the area and perimeter of the equilateral triangle using the given formulas:

  • Area = (sqrt(3) / 4) * side * side
  • Perimeter = 3 * side

The program then prints the values of the area and perimeter to the console using printf(). Finally, the program returns 0 to indicate successful program execution.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...