A rectangle has two important measurements: area, which represents the space enclosed by it, and perimeter, which represents the total length of its boundary.
- The area of a rectangle is calculated as length × width.
- The perimeter is calculated as 2 × (length + width).
Example
Input:
l = 10
b = 10
Output:
area = 100
perimeter = 40
Explanation:
The formula for the area of a rectangle is
Area = length*breadth => l*b
The formula for the perimeter of a rectangle is
Perimeter = 2*(length + breadth) => 2*(l+b)
Method 1: Direct Calculation
The area and perimeter are calculated directly inside the printf() statements.
#include <stdio.h>
int main()
{
int l = 10, b = 10;
printf("Area of rectangle is : %d", l * b);
printf("\nPerimeter of rectangle is : %d", 2 * (l + b));
return 0;
}
Output
Area of rectangle is : 100 Perimeter of rectangle is : 40
Method 2: Using Variables
Separate variables are used to store the calculated area and perimeter before displaying them.
#include <stdio.h>
int main()
{
int l = 10, b = 10;
int A, P;
A = l * b;
P = 2 * (l + b);
printf("Area of rectangle is : %d", A);
printf("\nPerimeter of rectangle is : %d", P);
return 0;
}
Output
Area of rectangle is : 100 Perimeter of rectangle is : 40
Method 3: Using functions
We can also calculate the area and perimeter using separate functions. This makes the program more modular and reusable.
#include <stdio.h>
int area(int a, int b)
{
int A;
A = a * b;
return A;
}
int perimeter(int a, int b)
{
int P;
P = 2 * (a + b);
return P;
}
int main()
{
int l = 10, b = 10;
printf("Area of rectangle is : %d", area(l, b));
printf("\nPerimeter of rectangle is : %d",
perimeter(l, b));
return 0;
}
Output
Area of rectangle is : 100 Perimeter of rectangle is : 40