C Program To Determine Shapes And Its Measurement
Understanding basic geometric shapes and calculating their properties is a fundamental skill in programming. In this article, you will learn how to create C programs to determine different shapes and compute their common measurements like area and perimeter.
Problem Statement
Many applications, from engineering design to game development, require the ability to identify shapes and calculate their dimensions. Manually performing these calculations for various shapes can be tedious and error-prone. The challenge lies in creating a robust and user-friendly program that can accurately compute measurements based on user input for different geometric figures.
Example
A simple program can calculate the area of a rectangle based on user input.
Enter the length of the rectangle: 10
Enter the width of the rectangle: 5
Area of the rectangle: 50.00
Background & Knowledge Prerequisites
To follow this tutorial, you should have a basic understanding of:
- C Programming Fundamentals: Variables, data types (especially
floatordoublefor precision), input/output operations (scanf,printf), and conditional statements (if-else,switch). - Basic Geometric Formulas:
- Rectangle: Area = length × width, Perimeter = 2 × (length + width)
- Circle: Area = π × radius², Circumference = 2 × π × radius
- Triangle: Perimeter = side1 + side2 + side3, Area (Heron's Formula) = √(s × (s - a) × (s - b) × (s - c)), where s is the semi-perimeter (a+b+c)/2.
- Mathematical Library: Knowledge of using the
math.hlibrary for functions likesqrt()andpow().
Use Cases or Case Studies
Determining shapes and their measurements in C programming has various practical applications:
- Architectural and Civil Engineering: Calculating the area of floor plans, land plots, or volumes of structural components.
- Game Development: Defining collision detection boundaries for objects (often simplified as rectangles or circles) or rendering game environments.
- Manufacturing and Fabrication: Estimating material requirements for cutting specific shapes from raw sheets, such as metals or fabrics.
- Geographic Information Systems (GIS): Computing areas of regions, perimeters of land parcels, or distances for mapping and spatial analysis.
- Computer Graphics: Drawing and manipulating shapes on a screen, where properties like size and position are fundamental.
Solution Approaches
We will implement a C program that allows the user to choose a shape and then calculates its area and perimeter (or circumference for a circle). The program will present a menu and handle input for different geometric figures.
Approach 1: Calculating Area and Perimeter of a Rectangle
This approach demonstrates how to compute the area and perimeter of a rectangle using its length and width.
// Rectangle Measurement
#include <stdio.h>
void calculateRectangle() {
float length, width, area, perimeter;
printf("\\n--- Rectangle Calculator ---\\n");
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
if (length <= 0 || width <= 0) {
printf("Error: Length and width must be positive values.\\n");
return;
}
area = length * width;
perimeter = 2 * (length + width);
printf("Area of the rectangle: %.2f\\n", area);
printf("Perimeter of the rectangle: %.2f\\n", perimeter);
}
Sample Output:
--- Rectangle Calculator ---
Enter the length of the rectangle: 10.5
Enter the width of the rectangle: 6
Area of the rectangle: 63.00
Perimeter of the rectangle: 33.00
Stepwise Explanation:
- Get Input: The program prompts the user to enter the
lengthandwidthof the rectangle. - Validate Input: It checks if the entered dimensions are positive. If not, an error message is displayed.
- Calculate Area: The
areais computed by multiplyinglengthandwidth. - Calculate Perimeter: The
perimeteris calculated as2 * (length + width). - Display Results: Both the calculated
areaandperimeterare printed to two decimal places.
Approach 2: Calculating Area and Circumference of a Circle
This approach calculates the area and circumference of a circle given its radius.
// Circle Measurement
#include <stdio.h>
#include <math.h> // Required for M_PI or custom PI definition
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
void calculateCircle() {
float radius, area, circumference;
printf("\\n--- Circle Calculator ---\\n");
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
if (radius <= 0) {
printf("Error: Radius must be a positive value.\\n");
return;
}
area = M_PI * radius * radius; // or pow(radius, 2)
circumference = 2 * M_PI * radius;
printf("Area of the circle: %.2f\\n", area);
printf("Circumference of the circle: %.2f\\n", circumference);
}
Sample Output:
--- Circle Calculator ---
Enter the radius of the circle: 7
Area of the circle: 153.94
Circumference of the circle: 43.98
Stepwise Explanation:
- Define PI:
M_PIis used frommath.hfor the value of Pi. A custom definition is provided as a fallback. - Get Input: The user is asked to enter the
radiusof the circle. - Validate Input: It checks if the radius is positive.
- Calculate Area: The
areais computed using the formulaπ * radius². - Calculate Circumference: The
circumferenceis calculated as2 * π * radius. - Display Results: The calculated
areaandcircumferenceare displayed with two decimal places.
Approach 3: Calculating Area and Perimeter of a Triangle
This approach computes the area (using Heron's formula) and perimeter of a triangle given its three side lengths.
// Triangle Measurement
#include <stdio.h>
#include <math.h> // Required for sqrt()
void calculateTriangle() {
float side1, side2, side3, perimeter, semiPerimeter, area;
printf("\\n--- Triangle Calculator ---\\n");
printf("Enter the length of side 1: ");
scanf("%f", &side1);
printf("Enter the length of side 2: ");
scanf("%f", &side2);
printf("Enter the length of side 3: ");
scanf("%f", &side3);
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
printf("Error: Side lengths must be positive values.\\n");
return;
}
// Triangle inequality theorem check
if (!((side1 + side2 > side3) && (side1 + side3 > side2) && (side2 + side3 > side1))) {
printf("Error: The given side lengths do not form a valid triangle.\\n");
return;
}
perimeter = side1 + side2 + side3;
semiPerimeter = perimeter / 2;
// Heron's formula for area
area = sqrt(semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) * (semiPerimeter - side3));
printf("Perimeter of the triangle: %.2f\\n", perimeter);
printf("Area of the triangle: %.2f\\n", area);
}
Sample Output:
--- Triangle Calculator ---
Enter the length of side 1: 3
Enter the length of side 2: 4
Enter the length of side 3: 5
Perimeter of the triangle: 12.00
Area of the triangle: 6.00
Stepwise Explanation:
- Get Input: The program asks the user to enter the lengths of the three sides (
side1,side2,side3). - Validate Input: It first checks if all side lengths are positive.
- Triangle Inequality Check: An important step is to verify if the given side lengths can form a valid triangle using the triangle inequality theorem (the sum of any two sides must be greater than the third side).
- Calculate Perimeter: The
perimeteris simply the sum of the three sides. - Calculate Semi-Perimeter: The
semiPerimeteris half of theperimeter. - Calculate Area: Heron's formula is applied to calculate the
areausing thesqrt()function frommath.h. - Display Results: The calculated
perimeterandareaare displayed.
Main Program Integration
Here's how these functions can be integrated into a single menu-driven program:
// Shape Measurement Calculator
#include <stdio.h>
#include <math.h>
// Define M_PI if not available in math.h (e.g., on some compilers)
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// Function to calculate rectangle properties
void calculateRectangle() {
float length, width, area, perimeter;
printf("\\n--- Rectangle Calculator ---\\n");
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
if (length <= 0 || width <= 0) {
printf("Error: Length and width must be positive values.\\n");
return;
}
area = length * width;
perimeter = 2 * (length + width);
printf("Area of the rectangle: %.2f\\n", area);
printf("Perimeter of the rectangle: %.2f\\n", perimeter);
}
// Function to calculate circle properties
void calculateCircle() {
float radius, area, circumference;
printf("\\n--- Circle Calculator ---\\n");
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
if (radius <= 0) {
printf("Error: Radius must be a positive value.\\n");
return;
}
area = M_PI * radius * radius;
circumference = 2 * M_PI * radius;
printf("Area of the circle: %.2f\\n", area);
printf("Circumference of the circle: %.2f\\n", circumference);
}
// Function to calculate triangle properties
void calculateTriangle() {
float side1, side2, side3, perimeter, semiPerimeter, area;
printf("\\n--- Triangle Calculator ---\\n");
printf("Enter the length of side 1: ");
scanf("%f", &side1);
printf("Enter the length of side 2: ");
scanf("%f", &side2);
printf("Enter the length of side 3: ");
scanf("%f", &side3);
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
printf("Error: Side lengths must be positive values.\\n");
return;
}
// Triangle inequality theorem check
if (!((side1 + side2 > side3) && (side1 + side3 > side2) && (side2 + side3 > side1))) {
printf("Error: The given side lengths do not form a valid triangle.\\n");
return;
}
perimeter = side1 + side2 + side3;
semiPerimeter = perimeter / 2;
area = sqrt(semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) * (semiPerimeter - side3));
printf("Perimeter of the triangle: %.2f\\n", perimeter);
printf("Area of the triangle: %.2f\\n", area);
}
int main() {
int choice;
do {
printf("\\n--- Shape Measurement Menu ---\\n");
printf("1. Calculate Rectangle\\n");
printf("2. Calculate Circle\\n");
printf("3. Calculate Triangle\\n");
printf("4. Exit\\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
calculateRectangle();
break;
case 2:
calculateCircle();
break;
case 3:
calculateTriangle();
break;
case 4:
printf("Exiting program. Goodbye!\\n");
break;
default:
printf("Invalid choice. Please enter a number between 1 and 4.\\n");
}
} while (choice != 4);
return 0;
}
Sample Output (Main Program Interaction):
--- Shape Measurement Menu ---
1. Calculate Rectangle
2. Calculate Circle
3. Calculate Triangle
4. Exit
Enter your choice: 1
--- Rectangle Calculator ---
Enter the length of the rectangle: 5.5
Enter the width of the rectangle: 2
Area of the rectangle: 11.00
Perimeter of the rectangle: 15.00
--- Shape Measurement Menu ---
1. Calculate Rectangle
2. Calculate Circle
3. Calculate Triangle
4. Exit
Enter your choice: 2
--- Circle Calculator ---
Enter the radius of the circle: 3.0
Area of the circle: 28.27
Circumference of the circle: 18.85
--- Shape Measurement Menu ---
1. Calculate Rectangle
2. Calculate Circle
3. Calculate Triangle
4. Exit
Enter your choice: 4
Exiting program. Goodbye!
Conclusion
Creating C programs to determine shapes and their measurements provides a foundational understanding of applying mathematical formulas in programming. By using functions and a menu-driven approach, we can build versatile tools that accurately calculate properties for various geometric figures. Proper input validation ensures the robustness of these applications, preventing erroneous calculations.
Summary
- C programs can effectively calculate geometric properties like area and perimeter/circumference.
- Rectangle: Area =
length * width, Perimeter =2 * (length + width). - Circle: Area =
π * radius², Circumference =2 * π * radius. Requiresmath.hforM_PIor manualPIdefinition. - Triangle: Perimeter =
side1 + side2 + side3, Area using Heron's formula (requiresmath.hforsqrt()). - Input validation is crucial to ensure dimensions are positive and form valid shapes.
- A menu-driven interface enhances user interaction for multi-shape calculators.