C Program – Area and Perimeter of Rectangle - Direct Calculation & Functions

Rectangle Area and Perimeter (Direct)

#include <stdio.h>
int main() {
    float length, breadth, area, perimeter;
    printf("Enter length and breadth of the rectangle: ");
    scanf("%f %f", &length, &breadth);
    area = length * breadth;
    perimeter = 2 * (length + breadth);
    printf("Area = %.2f\n", area);
    printf("Perimeter = %.2f\n", perimeter);
    return 0;
}
Enter length and breadth of the rectangle: 5 3
Area = 15.00
Perimeter = 16.00
        

This straightforward method calculates the area by multiplying length and breadth and computes the perimeter as twice the sum of the sides, printing both values for the user.

Rectangle Area and Perimeter Using Functions

#include <stdio.h>
float area(float l, float b) {
    return l * b;
}
float perimeter(float l, float b) {
    return 2 * (l + b);
}
int main() {
    float length, breadth;
    printf("Enter length and breadth of the rectangle: ");
    scanf("%f %f", &length, &breadth);
    printf("Area = %.2f\n", area(length, breadth));
    printf("Perimeter = %.2f\n", perimeter(length, breadth));
    return 0;
}
Enter length and breadth of the rectangle: 7.5 2.0
Area = 15.00
Perimeter = 19.00
        

Encapsulating the area and perimeter computations in separate functions makes the code modular and reusable. Each function takes length and breadth as parameters, returns the computed value, and is called from the main function.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...