Structure Assignment 10 — Create a Structure to Represent a Rectangle
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Create a Structure to Represent a Rectangle (Length, Width)

📑 On this page:
  • A rectangle is two numbers
  • The struct and its fields
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to model a rectangle with a small struct — just length and width
  • Why we use float for the sides, not int
  • How to fill the struct at declaration, or set each field afterwards
  • How to print the dimensions clearly, so they read like real measurements
  • How this struct becomes the starting point for area, perimeter, and comparison programs

A rectangle is two numbers

A rectangle is fully described by two numbers: its length and its width. That's it. Once you know those two, you know everything about the shape — its area, its perimeter, whether it's a square, how it compares to another rectangle. So it makes sense to store them together in one struct rather than as two separate variables.

This is the same idea as the point struct, just with different names. Instead of x and y, we have length and width. Both are floats, because rectangles rarely have integer dimensions in real programs — a table might be 1.5 metres long, a garden 12.7 metres wide. If you use int, you'd only be able to represent rectangles with whole-number sides, and any computation would chop off the fractional part.

The program itself is tiny: define the struct, declare one, fill in the sides, print them. It's the same pattern we've been using for points and books. The point of this assignment isn't the code — it's building the habit of seeing a rectangle as "two floats that travel together". Once you're used to that, the next assignment (print the dimensions) is just formatting, and the one after (area and perimeter) is a small step of arithmetic on the fields.

💡 In one line: struct rectangle { float length; float width; }; is the type. struct rectangle r = {10.5f, 4.2f}; is one rectangle. r.length and r.width are the two numbers.

A rectangle drawn with the longer side labelled length = 10.5 and the shorter side labelled width = 4.2. Both labels appear alongside the rectangle.

The struct and its fields

The struct is small and direct:

struct rectangle {
    float length;
    float width;
};
                                

Two floats, one for each side. Don't forget the semicolon after the closing brace — same as every struct. No arrays, no strings, no nesting. The whole type is two numbers with names.

Member Type Meaning Example
lengthfloatThe longer side (or any side you call length)r.length = 10.5f;
widthfloatThe shorter sider.width = 4.2f;

A note on naming. There's nothing in C that forces length to be longer than width. You could call the sides the other way around, or use base and height. The names are for humans reading the code. Pick something that matches how you think about the shape.

Complete C Program

Program: define a rectangle and print its sides

#include <stdio.h>

struct rectangle {
    float length;
    float width;
};

int main(void) {
    struct rectangle r = {10.5f, 4.2f};

    printf("Rectangle\n");
    printf("---------\n");
    printf("Length : %.2f\n", r.length);
    printf("Width  : %.2f\n", r.width);

    return 0;
}
                                    

And here's a version that reads the sides from the user, which is closer to what you'd write 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);

    printf("\nRectangle\n");
    printf("---------\n");
    printf("Length : %.2f\n", r.length);
    printf("Width  : %.2f\n", r.width);

    return 0;
}
                                    

The first version is the assignment answer — define the struct and show a rectangle. The second is what you'd actually write if you wanted to try different sizes without editing the source. Both end with the same printf lines; only the way the fields got filled is different.

Program Output

Rectangle
---------
Length : 10.50
Width  : 4.20
                                

And for the read-from-user version:

Enter length: 12.75
Enter width: 5.5

Rectangle
---------
Length : 12.75
Width  : 5.50
                                

Try a square — say 6 6 — and you'll see Length : 6.00 and Width : 6.00. The struct doesn't care whether it's a square or not; the distinction only shows up when you start computing things like area or checking if length equals width.

Step-by-Step Explanation

Small program, quick walk-through.

1. The struct definition

struct rectangle { float length; float width; }; — two floats, one for each side. The order matters for the initializer list, but not for anything else. If you flip the declaration order and use named fields in the initializer, nothing breaks. If you use positional fields, the values swap.

2. Declaring and filling

struct rectangle r = {10.5f, 4.2f}; creates a rectangle with length 10.5 and width 4.2. The f suffix on each number says "float, not double". Without it, C would treat the literals as doubles and quietly narrow them to floats when storing — not a bug, but worth avoiding for clarity.

3. Printing the sides

printf("Length : %.2f\n", r.length); and the same for r.width. The %.2f shows two decimal places, which is what makes 4.2 appear as 4.20 and 10.5 as 10.50. It looks more like a real measurement that way — nobody writes "4.2 metres" when they're taking down dimensions, they write "4.20 m".

4. Why not int?

Because rectangles in the real world have fractional sides all the time. A sheet of A4 paper is 29.7 cm × 21.0 cm. A door frame is 82.5 cm wide. If you use int, you'd round those to 30 and 82, and any area or perimeter computed from them would be off by hundreds of square centimetres. Floating-point is the natural fit for measurements.

5. Reading from the user

The scanf variant shows the same pattern for input: scanf("%f", &r.length) reads a float and stores it directly in the field. The & is essential — scanf needs the address of the field to write into it. This is the same as scanf on any other variable, just with the field name as the target.

6. Where this goes next

Once you have a rectangle struct, computing its area is one line: r.length * r.width. The perimeter is two lines: 2 * (r.length + r.width). Comparing two rectangles, checking if one is a square, finding the one with a bigger area — all of it is a small step of arithmetic on the fields. So this assignment is really about setting up the struct so that the next two assignments have a clean foundation.

7. The naming choice

You could have called the fields a and b — nothing in C would care. But length and width make the code read as "the length of r" and "the width of r", which is what you're thinking about. A struct is a small piece of vocabulary for your program, and choosing good names makes it easier to read six months later.

🎯 Remember this: a rectangle is two floats — length and width. Fill it with {10.5f, 4.2f} or set the fields one by one. Print with %.2f so the sides look like measurements. Reading from the user needs &r.length in the scanf.

Frequently Asked Questions

1. Should length always be the longer side?

Not really. In many programs, "length" and "width" are just labels — the math doesn't care. The only time it matters is if you write code that assumes length >= width, like a check "is this a landscape rectangle?". In that case you'd enforce the rule by swapping the fields if you read them in the wrong order. For this assignment, any two positive numbers are a valid rectangle.

2. Why floats and not ints?

Because real-world rectangles have fractional sides. A laptop is 32.5 cm × 22.7 cm, a book cover is 22.5 cm × 15 cm. If you use int, you'd have to round everything to whole numbers and any area or perimeter would be off. Floats keep the decimals, which is what you want for measurements. Int is fine for grid-based problems like chessboards or pixel coordinates, where the sides really are integers.

3. Why does 4.2 print as 4.20 and not 4.2?

Because %.2f prints exactly two decimal places, padding with zeros if needed. 4.2 becomes 4.20. If you want to drop the trailing zero, use %g instead, which picks the most compact form. But %.2f is more predictable — the printed values always have two decimals, which looks tidy for a list of measurements.

4. Can I have negative sides?

There's nothing in C that stops you — you could set r.length = -5.0f and the struct would happily accept it. But a rectangle with a negative side doesn't make geometric sense, and any area or perimeter computed from it would be wrong. Real programs usually validate the input: if (r.length <= 0 || r.width <= 0) { error }. For this assignment, assuming positive values is fine; the validation habit is worth adding in the next programs.

5. Can I have an array of rectangles?

Yes — struct rectangle rooms[5]; gives five rectangles. The loop pattern is the same as for books and points: fill each one, iterate with rooms[i].length and rooms[i].width. This is the natural next step if you want to compute the total area of a floor plan, for instance.

6. Is this struct used elsewhere in the series?

Yes. The next two assignments build on it: assignment 11 prints the dimensions cleanly (which is mostly what we did here, with a bit more formatting), and assignment 12 computes area and perimeter. After that, the rectangle struct is a useful example for comparing structs, passing them to functions, and working with arrays. It's a small, clean example that keeps showing up.

💡 Tip: After this, try adding a small check that prints "square" if r.length == r.width, otherwise "rectangle". It's just an if-else on the two fields. Then try printing a comparison like "This is a landscape rectangle" when length is greater than width. Small additions that make the program feel more useful.

📖 Related Tutorials

  • 11. Initialize and Display the Dimensions of a Rectangle Using a Structure
  • 12. Calculate the Area and Perimeter of a Rectangle Using a Structure
  • 9. Find the Distance Between Two Points Using a Structure
  • Defining a Structure
  • Accessing Structure Members
  • Structure Initialization
  • Array of Structures
  • All 25 Structure Assignments

Previous Topic: -->> 9. Find the Distance Between Two Points Using a Structure   ||   Next Topic: -->> 11. Initialize and Display the Dimensions of a Rectangle Using a Structure


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.