C program to find the area of a triangle
In this article, we are going to discuss how to find the area of a triangle. So let’s start!
Input:
Here, we are taking user input for the base of a triangle, For example, here we are taking 5.
we are taking user input for the height of a triangle, For example, here we are taking 8
Logic:
Before starting the program, we have to know about the area of the triangle that is :
area = (base * height )/2
Output:
So we are going to see this in two ways. One is by applying this formula directly and the second one is by using a user-defined function. So let’s discuss this one by one.
Step 1: Take two float-type variables to take input of height and base from the user. To print the area of the triangle simply use area. From the above program, we can simply see that we take three user inputs.
Step 2: After taking the input from the user simply use scanf () statement to store the value of a variable. We can see this from the above program.
Step 3: now just simply apply the formula that is :
Area = (base * height)/2;
Step 4: After applying the formula simply use printf() statement to get our output.
Method 1:
//C program to find the area of a triangle
#include<stdio.h>
int main(){
float height, base, area;
printf(“Enter base of triangle :”);
scanf(“%f”, &base);
printf(“Enter height of triangle :”);
scanf(“%f”, &height);
area = (base *height )/2;
printf(“Area of triangle is %F”, area);
return 0;
}
Output :
Enter height: 2
Enter base: 4
The area of the triangle is 4
Method 2:
//C program to calculate the area of the triangle using user define function.
#include<stdio.h>
float area(float base, float height){
return(base*height)/2;
}
int main(){
float base, height, a;
printf(“Enter height of triangle : “);
scanf(“%f”, &height);
printf(“Enter base of triangle :”);
scanf(“%f”, &base);
a = area(base,height);
printf(“Area of triangle is %f”, a);
return 0;
}
Output
Enter the height of the triangle: 12
Enter the base of the triangle: 4
The area of a triangle is 24.00000
In these ways, we simply understand how we can find out the area of a triangle by using this logic.
Step 1: create your own function and return the value of height and base in it. From the above example, we can see that we simply use the user to define a function in it.
Step 2: now go to the main function and take two float-type variables to get height and base from the user.
Step 3: After that give the values to the function. We can see that in the above program, we give the value of height and breadth to a.
Step 4: After the above step we simply print the a and finally we will get our desired output.
In this way, we simply understand how to find the area of a triangle in two ways. I hope this concept is clear to you. So for now keep learning and keep exploring.