Structure Assignment 12 — Calculate the Area and Perimeter of a Rectangle
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Calculate the Area and Perimeter of a Rectangle Using a Structure

📑 On this page:
  • Two small sums from one struct
  • The formulas, step by step
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to use the same two fields for two different calculations
  • Why area uses length * width but perimeter uses 2 * (length + width)
  • Why the results should be stored in a float or double, not an int
  • Why the area is measured in square units and the perimeter in linear units
  • How to lay out the output so it reads like a proper spec sheet

Two small sums from one struct

Once you have the length and width in a struct, computing the area and perimeter is just two small bits of arithmetic. The area is length times width — the amount of space inside the rectangle. The perimeter is the total distance around the edge, which is length + width + length + width, or 2 × (length + width) for short.

The same two fields feed both calculations. You don't need any new variables or any new struct — you just reach into r.length and r.width twice. That's the nice thing about a struct: once the data is in there, any function or any piece of code can use it to compute whatever it needs. The rectangle doesn't need to know it's being used for area or for perimeter; the fields are just numbers.

One small thing to watch: the results are areas and lengths, so they're not just bare numbers. The area of a 12.5 × 7.0 rectangle is 87.5 square units, and the perimeter is 39.0 units. You could ignore the units in the output, but printing "87.50 sq units" reads more clearly than just "87.50". It's a habit worth picking up early — numbers without units are ambiguous.

💡 In one line: area = r.length * r.width and perimeter = 2 * (r.length + r.width). Two formulas, same two fields.

A rectangle with length 12.5 and width 7.0. The inside is labelled Area = 87.5 square units, and the outline is labelled Perimeter = 39.0 units.

The formulas, step by step

There's nothing tricky here, but it helps to write the steps out so you can check your code against them.

  1. Get the length and width into the struct (either by filling it or reading from the user).
  2. Compute the area: r.length * r.width.
  3. Compute the perimeter: 2 * (r.length + r.width).
  4. Print all four values — length, width, area, perimeter — with two decimal places.

That's it. No loops, no conditions, no edge cases to worry about (well, one — if the user enters zero or a negative number, the result won't make sense as a rectangle, but we can talk about that in the FAQ).

Length Width Area Perimeter
1055030
12.57.087.539.0
663624
2.51.53.758.0
1000.550201

The third row is a square — area 36, perimeter 24. Notice that the area is bigger than the perimeter there, but in the last row the perimeter is much bigger than the area. That's normal: a long thin rectangle has a small area relative to its perimeter. A square has the largest area for a given perimeter, which is why a square plot of land feels "bigger" than a narrow strip with the same amount of fence.

Complete C Program

Program: compute area and perimeter from a rectangle struct

#include <stdio.h>

struct rectangle {
    float length;
    float width;
};

int main(void) {
    struct rectangle r = {12.5f, 7.0f};

    float area      = r.length * r.width;
    float perimeter = 2.0f * (r.length + r.width);

    printf("Rectangle Report\n");
    printf("----------------\n");
    printf("Length    : %.2f\n", r.length);
    printf("Width     : %.2f\n", r.width);
    printf("Area      : %.2f sq units\n", area);
    printf("Perimeter : %.2f units\n", perimeter);

    return 0;
}
                                    

And here's a version that reads the sides from the user, then computes the two results. This is closer to how you'd actually write it in a real program:

Variant: read the sides from the user

#include <stdio.h>

struct rectangle {
    float length;
    float width;
};

int main(void) {
    struct rectangle r;

    printf("Enter length: ");
    scanf("%f", &r.length);
    printf("Enter width: ");
    scanf("%f", &r.width);

    float area      = r.length * r.width;
    float perimeter = 2.0f * (r.length + r.width);

    printf("\nRectangle Report\n");
    printf("----------------\n");
    printf("Length    : %.2f\n", r.length);
    printf("Width     : %.2f\n", r.width);
    printf("Area      : %.2f sq units\n", area);
    printf("Perimeter : %.2f units\n", perimeter);

    return 0;
}
                                    

The two versions compute the same things. The only difference is where the sides come from — hardcoded in the first version, read from the user in the second. The formula part is identical, which is the point: once the data is in the struct, the arithmetic doesn't care where it came from.

Program Output

Rectangle Report
----------------
Length    : 12.50
Width     : 7.00
Area      : 87.50 sq units
Perimeter : 39.00 units
                                

And for the user-input version:

Enter length: 5
Enter width: 3

Rectangle Report
----------------
Length    : 5.00
Width     : 3.00
Area      : 15.00 sq units
Perimeter : 16.00 units
                                

Try a square like 6 × 6 to see both results line up. Try a very long thin rectangle like 100 × 0.5 — you'll see a big perimeter (201) and a modest area (50), which matches the shape: lots of edge, not much inside.

Step-by-Step Explanation

Quick walk-through of the main version.

1. The struct

Same struct rectangle as the last two assignments. Length and width, both floats. Nothing new here.

2. Filling the struct

struct rectangle r = {12.5f, 7.0f}; creates a rectangle with length 12.5 and width 7.0. Same one-line fill we've been using.

3. The area

float area = r.length * r.width; gives 12.5 × 7.0 = 87.5. The result is stored in a float, which is fine for typical rectangles. If you wanted extra precision (say, for surveying), you'd use a double instead. For classroom sizes, float is plenty.

4. The perimeter

float perimeter = 2.0f * (r.length + r.width); gives 2 × (12.5 + 7.0) = 2 × 19.5 = 39.0. The 2.0f has an f for the same reason we've been adding it elsewhere — it keeps everything as float. The parentheses around r.length + r.width are essential. Without them, you'd compute 2 × r.length + r.width, which is 32 instead of 39.

5. Printing the report

Four printf lines, one for each value. The labels are padded with spaces so they line up in a column — "Length :" and "Width :" and "Area :" and "Perimeter :" are all the same width up to the colon. That's a small formatting touch, but it makes the output look like a proper report instead of a jumble of numbers.

6. Why the units matter in the labels

"Area: 87.50" is a number. "Area: 87.50 sq units" tells you what the number means. It's not required by the compiler, but it's the kind of detail that makes output readable. Real programs print "12.50 cm²" or "87.50 m²" depending on the units. Here we don't know the units, so "sq units" is a safe way of saying "this is an area, not a length".

7. Why not int?

If the sides were ints, the area would also be an int. That works for whole-number rectangles, but the moment you have decimals — 12.5, 7.0 — the fractional parts get lost, and the area comes out wrong. 12.5 × 7.0 as integers is 12 × 7 = 84, not 87.5. So keep the fields and the results as floats. It's simpler and correct.

🎯 Remember this: area is r.length * r.width; perimeter is 2 * (r.length + r.width). Watch the parentheses — they make the difference between 39 and 32. Use floats for both sides and results. Print with units in the labels so the output reads clearly.

Frequently Asked Questions

1. Why is the perimeter formula 2 × (length + width)?

Because a rectangle has two lengths and two widths, one of each on opposite sides. So the total distance around the edge is length + width + length + width, which simplifies to 2 × (length + width). If you forget the parentheses, you compute "2 × length + width", which is only one length and one width — not the whole edge.

2. What's the difference between area and perimeter?

Area is the space inside the rectangle, measured in square units (cm², m², sq units). Perimeter is the distance around the edge, measured in linear units (cm, m, units). For a 3 × 4 rectangle, area = 12 square units and perimeter = 14 units. They're different quantities — the fact that both happen to be computed from the same two numbers doesn't mean they measure the same thing.

3. What happens if I enter a negative number?

The program will compute a negative area and a negative (or zero) perimeter. Both are meaningless as a rectangle. A real program would check the input and reject anything ≤ 0: if (r.length <= 0 || r.width <= 0) { error }. For a teaching example, assuming positive numbers is fine, but this is a good habit to pick up as you go.

4. Should I use float or double for area and perimeter?

Either works. float has about 7 decimal digits of precision, which is plenty for typical rectangles. double has about 15, which is more than enough. The struct uses floats, so the results come out as floats by default; sticking with float is fine. If you ever work with large coordinates or many multiplications, double is worth the extra precision.

5. Why does the area come out as 87.50 and not 87.5?

Because %.2f always shows two decimal places. 87.5 becomes 87.50. Same as with length and width — the two-decimal format keeps the output consistent and looks tidier in a table. If you want to drop the trailing zero, use %g instead, but for a report-style output, %.2f reads better.

6. Can I write this as a function?

Yes, and it's actually a good idea. Something like float rectangle_area(struct rectangle r) { return r.length * r.width; } is a small, reusable function. Then you call rectangle_area(rect) wherever you need it. The struct is small, so passing it by value is fine — for a bigger struct, you'd pass a pointer. This is the kind of thing that turns a small program into a well-organized one.

💡 Tip: After this, try adding a "diagonal" calculation: sqrt(r.length*r.length + r.width*r.width) from math.h. It's the same idea as the distance program, just applied to the two sides of a rectangle. Then try taking two rectangles and printing which has a bigger area — one if-else on the two area values, and you've got a comparison program.

📖 Related Tutorials

  • 10. Create a Structure to Represent a Rectangle
  • 11. Initialize and Display the Dimensions of a Rectangle Using a Structure
  • 13. Create a Structure to Represent a Date
  • 9. Find the Distance Between Two Points Using a Structure
  • Accessing Structure Members
  • Structures and Functions
  • Array of Structures
  • All 25 Structure Assignments

Previous Topic: -->> 11. Initialize and Display the Dimensions of a Rectangle Using a Structure   ||   Next Topic: -->> 13. Create a Structure to Represent a Date


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.