C Online Compiler
Example: Calculate Area and Perimeter of a Rectangle in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Calculate Area and Perimeter of a Rectangle #include <stdio.h> // Required for input/output functions int main() { // Step 1: Declare variables to store length, width, area, and perimeter. // Using float allows for non-integer dimensions. float length; float width; float area; float perimeter; // Step 2: Prompt the user to enter the length of the rectangle. printf("Enter the length of the rectangle: "); // Step 3: Read the length value from the user. scanf("%f", &length); // Step 4: Prompt the user to enter the width of the rectangle. printf("Enter the width of the rectangle: "); // Step 5: Read the width value from the user. scanf("%f", &width); // Step 6: Calculate the area of the rectangle. // Formula: Area = length * width area = length * width; // Step 7: Calculate the perimeter of the rectangle. // Formula: Perimeter = 2 * (length + width) perimeter = 2 * (length + width); // Step 8: Display the calculated area and perimeter to the user. // %.2f formats the float to two decimal places. printf("\nArea of the rectangle: %.2f square units\n", area); printf("Perimeter of the rectangle: %.2f units\n", perimeter); return 0; // Indicate successful program execution }
Output
Clear
ADVERTISEMENTS