The following C program demonstrates how to implement a function to calculate the area of a rectangle. This program takes the length and width of the rectangle as input from the user and then uses a custom function to calculate the area.
Program Code
// Function to calculate the area of a rectangle
float calculateArea(float length, float width) {
return length * width;
}
int main() {
float length, width, area;
// Prompt the user to enter the length and width of the rectangle
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
// Calculate the area of the rectangle using the custom function
area = calculateArea(length, width);
// Display the calculated area
printf("The area of the rectangle is: %.2f\n", area);
return 0;
}
How the Program Works
This C program consists of two main components: the `calculateArea` function and the `main` function.
The `calculateArea` Function
The `calculateArea` function takes two arguments, `length` and `width`, which represent the dimensions of the rectangle. It returns the calculated area by multiplying the length and width.
The `main` Function
The `main` function is the entry point of the program. It prompts the user to enter the length and width of the rectangle using `printf` and `scanf` statements. The entered values are stored in the `length` and `width` variables.
Next, the `main` function calls the `calculateArea` function, passing the `length` and `width` variables as arguments. The calculated area is stored in the `area` variable.
Finally, the `main` function displays the calculated area using a `printf` statement.
Example Output
Here's an example output of the program:
Enter the length of the rectangle: 5
Enter the width of the rectangle: 3
The area of the rectangle is: 15.00
FAQs
Q: What is the purpose of the `calculateArea` function?
A: The `calculateArea` function calculates the area of a rectangle given its length and width.
Q: How does the program handle invalid input?
A: The program does not include input validation. If the user enters invalid input, the program may produce incorrect results or crash.
Q: Can the program be modified to calculate the area of other shapes?
A: Yes, the program can be modified to calculate the area of other shapes by adding additional functions or modifying the existing `calculateArea` function.
Comments
Post a Comment