C Program To Find Area Of Circle Square And Rectangle Using Function
Calculating the area of different geometric shapes is a fundamental task in programming. Organizing these calculations using functions can significantly improve code readability, reusability, and maintainability. In this article, you will learn how to implement C programs to find the area of a circle, square, and rectangle using separate, well-defined functions.
Problem Statement
In many applications, there's a need to compute the areas of basic geometric shapes like circles, squares, and rectangles. A common challenge arises when these calculations are repeated throughout a program, leading to duplicated code. For instance, a CAD application might need to calculate areas for multiple components, or a simple geometry tool might offer various area computations. Duplicating code for each shape's area calculation makes the program harder to read, debug, and update.
Example
The final program will allow a user to choose a shape and then provide its dimensions to calculate and display the area, like this:
Enter the shape for which to calculate area:
1. Circle
2. Square
3. Rectangle
Enter your choice (1-3): 1
Enter the radius of the circle: 5
Area of the circle with radius 5.00 is: 78.50
Enter the shape for which to calculate area:
1. Circle
2. Square
3. Rectangle
Enter your choice (1-3): 2
Enter the side length of the square: 7
Area of the square with side 7.00 is: 49.00
Background & Knowledge Prerequisites
To understand this article, readers should have a basic understanding of:
- C Programming Basics: Variables, data types (especially
floatordoublefor precision). - Functions: How to declare, define, and call functions, including passing arguments and returning values.
- Standard Input/Output: Using
printf()for output andscanf()for input. - Conditional Statements: Basic
if-elseorswitchstatements for menu-driven programs. - Math Library: Basic knowledge of
M_PIconstant fromfor circle calculations.
Use Cases or Case Studies
Area calculations are crucial in various real-world scenarios:
- Construction and Architecture: Determining the amount of material needed for flooring, roofing, or painting rooms and structures.
- Urban Planning: Calculating land usage, green spaces, or paved areas within a city layout.
- Game Development: Collision detection, rendering object sizes, or defining play areas in a game engine.
- Engineering Design: Sizing components, calculating stress distribution over a surface, or estimating fluid flow in pipes.
- Agriculture: Measuring field sizes for crop yield estimation or fertilizer application planning.
Solution Approaches
We will focus on a structured approach using separate functions for each shape's area calculation, integrated into a menu-driven program.
Approach 1: Calculating Area Using Separate Functions
This approach involves creating distinct functions for calculating the area of a circle, square, and rectangle. Each function will take the necessary dimensions as arguments and return the computed area. This promotes modularity and makes the main program cleaner.
- One-line summary: Define and use dedicated functions (
areaCircle,areaSquare,areaRectangle) to encapsulate the area calculation logic for each shape.
// Area Calculator using Functions
#include <stdio.h> // For printf, scanf
#include <math.h> // For M_PI (pi constant)
// Function to calculate the area of a circle
// Parameters: radius (float)
// Returns: area of the circle (float)
float areaCircle(float radius) {
return M_PI * radius * radius;
}
// Function to calculate the area of a square
// Parameters: side (float)
// Returns: area of the square (float)
float areaSquare(float side) {
return side * side;
}
// Function to calculate the area of a rectangle
// Parameters: length (float), width (float)
// Returns: area of the rectangle (float)
float areaRectangle(float length, float width) {
return length * width;
}
int main() {
int choice;
float radius, side, length, width;
float resultArea;
// Step 1: Display menu to the user
printf("Enter the shape for which to calculate area:\\n");
printf("1. Circle\\n");
printf("2. Square\\n");
printf("3. Rectangle\\n");
printf("Enter your choice (1-3): ");
scanf("%d", &choice);
// Step 2: Process user's choice using a switch statement
switch (choice) {
case 1:
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
resultArea = areaCircle(radius); // Call the areaCircle function
printf("Area of the circle with radius %.2f is: %.2f\\n", radius, resultArea);
break;
case 2:
printf("Enter the side length of the square: ");
scanf("%f", &side);
resultArea = areaSquare(side); // Call the areaSquare function
printf("Area of the square with side %.2f is: %.2f\\n", side, resultArea);
break;
case 3:
printf("Enter the length of the rectangle: ");
printf("Enter the width of the rectangle: ");
scanf("%f", &length);
scanf("%f", &width);
resultArea = areaRectangle(length, width); // Call the areaRectangle function
printf("Area of the rectangle with length %.2f and width %.2f is: %.2f\\n", length, width, resultArea);
break;
default:
printf("Invalid choice. Please enter a number between 1 and 3.\\n");
break;
}
return 0;
}
- Sample Output:
Enter the shape for which to calculate area:
1. Circle
2. Square
3. Rectangle
Enter your choice (1-3): 1
Enter the radius of the circle: 4.5
Area of the circle with radius 4.50 is: 63.59
Enter the shape for which to calculate area:
1. Circle
2. Square
3. Rectangle
Enter your choice (1-3): 3
Enter the length of the rectangle: 10
Enter the width of the rectangle: 5.5
Area of the rectangle with length 10.00 and width 5.50 is: 55.00
- Stepwise explanation for clarity:
- Include Headers:
stdio.his included for input/output operations (printf,scanf), andmath.his included to access theM_PIconstant (the value of Pi). - Define
areaCircleFunction: This function takes afloatradiusas input and returns the calculated area using the formulaM_PI * radius * radius. - Define
areaSquareFunction: This function takes afloatsideas input and returns the area usingside * side. - Define
areaRectangleFunction: This function takes twofloatarguments,lengthandwidth, and returns their product as the area. mainFunction:
- It declares variables to store user
choiceand the dimensions (radius,side,length,width), along withresultArea. - A menu is displayed to the user using
printf. -
scanfreads the user'schoice. - A
switchstatement handles the user's input: - Case 1 (Circle): Prompts for
radius, callsareaCircle()with the provided radius, and prints the result. - Case 2 (Square): Prompts for
side, callsareaSquare()with the provided side, and prints the result. - Case 3 (Rectangle): Prompts for
lengthandwidth, callsareaRectangle()with these values, and prints the result. -
default: Handles invalid choices. -
%.2finprintfformats the floating-point output to two decimal places for better readability.
Conclusion
Using functions to calculate the area of different shapes significantly improves code organization and efficiency. Each function encapsulates a specific piece of logic, making the code easier to understand, test, and reuse. This modular approach is a cornerstone of good programming practices, leading to more robust and maintainable applications.
Summary
- Functions promote code modularity, making programs easier to read and maintain.
- Separate functions (
areaCircle,areaSquare,areaRectangle) can be defined for specific tasks. - Functions take input parameters (e.g., radius, side, length, width) and return a calculated value (the area).
- The
mainfunction orchestrates the program flow, often using a menu and conditional statements (switch) to call the appropriate area calculation function based on user input. - Using
floatordoubledata types ensures precision for geometric calculations, andM_PIfrommath.hprovides an accurate value for Pi.