C Program To Calculate Area Of Circle Rectangle And Triangle Using Function
Calculating the area of various geometric shapes is a common task in programming. In this article, you will learn how to write a C program that calculates the area of a circle, rectangle, and triangle by leveraging user-defined functions for each specific shape.
Problem Statement
A frequent challenge in programming involves performing specific mathematical calculations multiple times or based on different user inputs. Directly embedding the calculation logic repeatedly can lead to redundant code that is difficult to read, maintain, and debug. Encapsulating these distinct area calculation logics within separate functions allows for code reusability, promotes modularity, and makes the program more organized.
Example
Here's an example of what the program's execution would look like, demonstrating its ability to calculate areas for different shapes based on user input:
--- Circle Area Calculation ---
Enter the radius of the circle: 5
Area of the circle: 78.54
--- Rectangle Area Calculation ---
Enter the length of the rectangle: 10
Enter the width of the rectangle: 4
Area of the rectangle: 40.00
--- Triangle Area Calculation ---
Enter the base of the triangle: 7
Enter the height of the triangle: 6
Area of the triangle: 21.00
Background & Knowledge Prerequisites
To understand and implement this program, readers should have a basic understanding of:
- C Programming Fundamentals: Variables, data types (especially
doublefor precision), input/output operations (printf,scanf). - Functions in C: How to declare, define, and call functions, including passing arguments and returning values.
-
math.hLibrary: Awareness thatM_PI(for the value of Pi) is typically found in themath.hheader file.
Use Cases
Calculating the area of geometric shapes has numerous practical applications across various fields:
- Engineering and Architecture: Determining material requirements for construction, designing structures, or planning layouts.
- Game Development: Implementing collision detection, pathfinding algorithms, or rendering game environments.
- Computer-Aided Design (CAD): Analyzing properties of designed objects, such as surface area or volume estimations.
- Educational Tools: Creating interactive learning applications for mathematics and geometry.
- Data Visualization: Representing data points within specific graphical boundaries or scaling elements accurately.
Solution Approaches
This article focuses on a straightforward and highly effective approach: using dedicated functions for each area calculation.
Calculating Areas with Dedicated Functions
This approach defines distinct functions for calculating the area of a circle, rectangle, and triangle. This promotes modularity, makes the code readable, and allows for easy reuse of the area calculation logic whenever needed.
Code Example
// Area Calculator using Functions
#include <stdio.h>
#include <math.h> // Required for M_PI (Pi value)
// Function to calculate the area of a circle
// Takes the radius as input and returns the area
double calculateCircleArea(double radius) {
return M_PI * radius * radius;
}
// Function to calculate the area of a rectangle
// Takes length and width as input and returns the area
double calculateRectangleArea(double length, double width) {
return length * width;
}
// Function to calculate the area of a triangle
// Takes base and height as input and returns the area
double calculateTriangleArea(double base, double height) {
return 0.5 * base * height;
}
int main() {
// Step 1: Declare variables for inputs and results
double radius, length, width, base, height;
double circleArea, rectangleArea, triangleArea;
// Step 2: Get user input for circle and calculate its area
printf("--- Circle Area Calculation ---\\n");
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
circleArea = calculateCircleArea(radius); // Call the function
printf("Area of the circle: %.2f\\n\\n", circleArea);
// Step 3: Get user input for rectangle and calculate its area
printf("--- Rectangle Area Calculation ---\\n");
printf("Enter the length of the rectangle: ");
scanf("%lf", &length);
printf("Enter the width of the rectangle: ");
scanf("%lf", &width);
rectangleArea = calculateRectangleArea(length, width); // Call the function
printf("Area of the rectangle: %.2f\\n\\n", rectangleArea);
// Step 4: Get user input for triangle and calculate its area
printf("--- Triangle Area Calculation ---\\n");
printf("Enter the base of the triangle: ");
scanf("%lf", &base);
printf("Enter the height of the triangle: ");
scanf("%lf", &height);
triangleArea = calculateTriangleArea(base, height); // Call the function
printf("Area of the triangle: %.2f\\n\\n", triangleArea);
return 0;
}
Sample Output
--- Circle Area Calculation ---
Enter the radius of the circle: 7.5
Area of the circle: 176.71
--- Rectangle Area Calculation ---
Enter the length of the rectangle: 12
Enter the width of the rectangle: 5
Area of the rectangle: 60.00
--- Triangle Area Calculation ---
Enter the base of the triangle: 8.2
Enter the height of the triangle: 4.5
Area of the triangle: 18.45
Stepwise Explanation
- Include Headers:
-
stdio.h: Provides standard input/output functions likeprintfandscanf. -
math.h: Provides mathematical constants and functions, specificallyM_PI(the value of Pi) for circle area calculation.
- Define
calculateCircleAreaFunction:
-
double calculateCircleArea(double radius): Declares a function namedcalculateCircleAreathat accepts adoubletype argument (radius) and returns adoubletype value (the area). -
return M_PI * radius * radius;: Computes the area using the formula $\pi \times \text{radius}^2$ and returns the result.
- Define
calculateRectangleAreaFunction:
-
double calculateRectangleArea(double length, double width): Declares a function that takes twodoublearguments (length, width) and returns adoublevalue. -
return length * width;: Calculates the area using the formula $\text{length} \times \text{width}$ and returns it.
- Define
calculateTriangleAreaFunction:
-
double calculateTriangleArea(double base, double height): Declares a function that takes twodoublearguments (base, height) and returns adoublevalue. -
return 0.5 * base * height;: Computes the area using the formula $0.5 \times \text{base} \times \text{height}$ and returns the result.
mainFunction - Program Execution Start:
- Variable Declaration:
double radius, length, width, base, height;declares variables to store user inputs for each shape.double circleArea, rectangleArea, triangleArea;declares variables to store the calculated areas. Usingdoubleensures higher precision for calculations. - Circle Calculation Block:
- Prompts the user to enter the radius.
- Reads the input using
scanf("%lf", &radius);(%lfis used fordouble). - Calls
calculateCircleArea(radius)to get the area, storing it incircleArea. - Prints the calculated area, formatted to two decimal places (
.2f). - Rectangle Calculation Block:
- Similar to the circle block, it prompts for length and width, reads inputs, calls
calculateRectangleArea, and displays the result. - Triangle Calculation Block:
- Similarly, it prompts for base and height, reads inputs, calls
calculateTriangleArea, and displays the result. -
return 0;: Indicates successful program execution.
Conclusion
By using distinct functions for each area calculation, the C program demonstrates principles of modularity and reusability. This approach leads to cleaner, more organized, and easier-to-maintain code, which is a fundamental practice in software development. Separating concerns into functions makes the program extensible, allowing new shape calculations to be added without altering existing logic.
Summary
- Functions in C provide a powerful way to organize code, preventing repetition and improving readability.
- Dedicated functions like
calculateCircleArea,calculateRectangleArea, andcalculateTriangleAreaencapsulate specific logic. - The
math.hlibrary is essential for accessing mathematical constants likeM_PIfor precise calculations. - Using
doublefor numerical inputs and outputs ensures accuracy for geometric calculations. - Modular code is easier to test, debug, and expand with new features.