C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

C Program: Area and Perimeter of a Rectangle

Introduction

A rectangle is a 2D geometric shape with opposite sides equal and four right angles.
To solve geometry problems in programming, we often calculate the area (amount of space covered) and perimeter (total boundary length).

The formulas are:

Area = Length × Width   

Perimeter = 2 × (Length + Width)  

In this program, we take the length and width of a rectangle as input from the user and compute both the area and perimeter.

C Program: Area and Perimeter of a Rectangle

C

#include <stdio.h>   // Standard I/O header

 

int main() {

    float length, width, area, perimeter;

 

    // Input from user

    printf("Enter the length of the rectangle: ");

    scanf("%f", &length);

 

    printf("Enter the width of the rectangle: ");

    scanf("%f", &width);

 

    // Calculations

    area = length * width;

    perimeter = 2 * (length + width);

 

    // Output results

    printf("Area of the rectangle      = %.2f\n", area);

    printf("Perimeter of the rectangle = %.2f\n", perimeter);

 

    return 0; // Successful termination

}

Output

 
OUTPUT 1 :
Enter the length of the rectangle: 10
Enter the width of the rectangle: 5
Area of the rectangle      = 50.00
Perimeter of the rectangle = 30.00

OUTPUT 2 :
Enter the length of the rectangle: 7.5
Enter the width of the rectangle: 3.2
Area of the rectangle      = 24.00
Perimeter of the rectangle = 21.40

Explanation:

  1. Variable declaration
    • float length, width, area, perimeter; stores user input and computed results.
  2. Input values
    • scanf("%f", &length); → reads rectangle length.
    • scanf("%f", &width); → reads rectangle width.
  3. Formulas applied
    • area = length * width;
    • perimeter = 2 * (length + width);
  4. Output
    • Results are printed with %.2f to show two decimal places.