Introduction Assignment 6 — Area of a Rectangle by Accepting Length and Width
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Area of a Rectangle by Accepting Length and Width

📑 On this page:
  • The rectangle area formula
  • Designing the program
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • The rectangle area formula: A = length × width
  • How to read two floating-point values with a single scanf call
  • Why double is the right type for dimensions
  • How to format output to two decimal places
  • How to handle invalid input (negative dimensions)
  • How to extend the program to compute perimeter alongside area

The rectangle area formula

A rectangle is a quadrilateral with four right angles — opposite sides are equal, and adjacent sides are perpendicular. The area of a rectangle is the space enclosed by its four sides. If its length is L and its width is W, the area is:

Area = Length × Width

The formula is intuitive: a rectangle with length 5 and width 3 can be tiled by 15 unit squares arranged in 5 rows of 3. The area is 15 square units. For a 2.5 × 4 rectangle, the area is 10 — even though the dimensions are fractional, the product is a whole number (a coincidence here, but the formula handles fractions naturally).

The units matter. If length is in centimeters and width is in centimeters, area is in square centimeters. If length is in meters and width is in meters, area is in square meters. Mixed units — length in centimeters, width in inches — require conversion first. This is a common source of errors in real applications; our program assumes the inputs are in the same unit, and we document that assumption in the prompt.

The program reads length and width as double (to handle fractional dimensions), multiplies them, and prints the result. It's the simplest possible "input → compute → output" program, which makes it an ideal first exercise after the data-type and swap assignments. It exercises scanf, printf, arithmetic, and type selection all at once.

💡 In one line: area of a rectangle = length × width. Read both as double, multiply, print with %.2lf. That's the whole program.

A rectangle with length 5 and width 3, labelled with the area formula A = length × width = 15.

Designing the program

The design has four decisions that matter:

Decision Choice Reason
Variable typedoubleDimensions can be fractional (e.g., 2.5 m). int would truncate.
Number of variableslength, width, areaDescriptive names; three variables, one for each quantity.
Input methodscanf("%lf %lf", &length, &width)Reads both dimensions in one call; whitespace between them is flexible.
Output format%.2lfTwo decimal places is standard for measurement output.

The names length, width, and area are chosen to match the formula. A reader sees area = length * width; and immediately knows what's happening — the code is self-documenting. This is a small but important point: in a program this simple, good naming eliminates the need for comments almost entirely.

The scanf("%lf %lf", &length, &width) reads both values in one call. The user can type 5.0 3.0, or 5 then Enter then 3 — both work. The space between the two %lf specifiers means "skip any whitespace before reading the second number," which is standard behavior for %lf anyway.

🎯 Key idea: use double for any real-world measurement. Even if you expect whole-number inputs, users can enter 3.5. Using double from the start avoids a whole class of bugs — no truncation, no silent wrong answers, no need to fix the code later when fractional input appears.

Complete C Program

Program: read length and width, print area

#include <stdio.h>

int main(void) {
    double length;
    double width;
    double area;

    /* Prompt and read the two dimensions */
    printf("Enter the length of the rectangle: ");
    scanf("%lf", &length);

    printf("Enter the width of the rectangle: ");
    scanf("%lf", &width);

    /* Check for invalid dimensions */
    if (length <= 0 || width <= 0) {
        printf("Error: length and width must be positive.\n");
        return 1;
    }

    /* Compute the area */
    area = length * width;

    /* Print the result with two decimal places */
    printf("Area of the rectangle = %.2lf\n", area);

    return 0;
}
                                    

This version reads each dimension with a separate prompt, which is more user-friendly than a combined prompt. It also checks for invalid input (non-positive dimensions) — a small but worthwhile robustness measure. For a teaching exercise, you might omit the check; for anything approaching real code, include it.

And here's a more compact version that reads both dimensions in one call and also computes the perimeter:

Variant: compact version with perimeter

#include <stdio.h>

int main(void) {
    double length, width, area, perimeter;

    printf("Enter length and width (separated by space): ");
    scanf("%lf %lf", &length, &width);

    area = length * width;
    perimeter = 2 * (length + width);

    printf("Area      = %.2lf\n", area);
    printf("Perimeter = %.2lf\n", perimeter);

    return 0;
}
                                    

The perimeter is a nice extra — it demonstrates that the same two inputs can produce multiple derived quantities. The perimeter formula is P = 2(L + W). For a 5 × 3 rectangle, area is 15 and perimeter is 16. Both values are useful in practical problems (e.g., paint for the floor vs. fence for the boundary).

Program Output

Here is typical output for a 5 × 3 rectangle:

Enter the length of the rectangle: 5
Enter the width of the rectangle: 3
Area of the rectangle = 15.00
                                

Check: 5 × 3 = 15. Correct. The output has two decimal places (15.00) because of %.2lf, even though the result is a whole number.

For a fractional rectangle, 2.5 × 4:

Enter the length of the rectangle: 2.5
Enter the width of the rectangle: 4
Area of the rectangle = 10.00
                                

Check: 2.5 × 4 = 10. Correct. The double types handle the fractional input correctly — no truncation, no rounding error at this scale.

For 1.5 × 2.5 (both fractional, giving a fractional result):

Enter the length of the rectangle: 1.5
Enter the width of the rectangle: 2.5
Area of the rectangle = 3.75
                                

Check: 1.5 × 2.5 = 3.75. Correct. The two decimals in the output (3.75) reflect the precision of the calculation.

For a degenerate input (zero or negative):

Enter the length of the rectangle: -5
Enter the width of the rectangle: 3
Error: length and width must be positive.
                                

The validation catches the negative length and reports the error. Without it, the program would print "Area = -15.00," which is mathematically meaningless for a real rectangle.

And the variant with perimeter:

Enter length and width (separated by space): 5 3
Area      = 15.00
Perimeter = 16.00
                                

Check: Area = 5 × 3 = 15, Perimeter = 2 × (5 + 3) = 16. Both correct.

🔍 Try this: run the program with very large dimensions — say, 1000000 × 1000000. The area is 1012, well within the range of double. Now try very small dimensions — 0.001 × 0.001 gives 1e-6, which prints as 0.00 with %.2lf. If you need more precision for small values, use %.6lf or %g. This is the tension between clean output and precise output — %.2lf is fine for typical dimensions, but not for all cases.

Step-by-Step Explanation

Let's walk through the program line by line, then discuss the design choices.

1. The include

#include <stdio.h> — needed for printf and scanf. As before, this is a preprocessor directive that pastes the standard I/O header into the source before compilation.

2. The declarations

double length;, double width;, double area; — three floating-point variables. Each occupies 8 bytes on typical systems, capable of holding values with about 15 significant decimal digits and a range of roughly ±10±308. For typical measurements (dimensions in centimeters, meters, feet, etc.), this is far more precision and range than needed.

Could you use float instead? Yes — for dimensions up to a few thousand units, float's 7-digit precision is fine. But double is the default for floating-point literals in C and requires no extra typing, so it's the simpler choice. Using double also avoids subtle bugs from accidental truncation if someone later increases the input range.

Could you use int? Only if dimensions are always whole numbers. The moment a user enters 2.5 (common in real measurements), scanf("%d", &length) would read 2 and ignore the .5, silently giving the wrong area. So double is the safe choice.

3. Reading the length

printf("Enter the length of the rectangle: "); — prompts the user. The trailing space (no \n) means the user will type on the same line as the prompt, which is standard for interactive input. The scanf("%lf", &length); reads a double into length. The %lf specifier matches double; the & gives scanf the address to write to.

If the user types something that isn't a number (e.g., "abc"), scanf fails to read, leaves length uninitialized, and returns 0. The program would then proceed with garbage, producing nonsense output. For a beginner program, this is often acceptable; for robust code, you check scanf's return value. We'll come back to this in the FAQ.

4. Reading the width

Same pattern: prompt, then scanf("%lf", &width);. Two separate prompts and two separate reads is more user-friendly than a combined one, because the user knows exactly which input they're providing at each step.

5. Validating the input

if (length <= 0 || width <= 0) { ... } — checks that both dimensions are positive. A rectangle with a zero or negative dimension is degenerate (zero area, or meaningless). The check catches these cases and reports an error before the calculation. Returning 1 from main signals failure to the shell, which is conventional for programs that encounter errors.

Could you skip this check? Yes — for a teaching exercise, the check is often omitted. But adding it demonstrates a key principle: don't trust user input. A user can (and will) type something invalid; the program should handle that gracefully rather than producing a nonsensical result.

6. Computing the area

area = length * width; — the core of the program. Both operands are double, so the multiplication is done in double precision. The result is stored in area, which is also double. No implicit conversions, no truncation, no surprise.

The multiplication is commutative (length * width == width * length), so the order doesn't matter. Using length * width reads naturally — it matches the formula.

7. Printing the result

printf("Area of the rectangle = %.2lf\n", area); — prints the label, then the value of area with exactly two decimal places, then a newline. The %.2lf specifier: % starts the format, lf says double, and .2 means "two digits after the decimal point." So 15.0 becomes "15.00", and 3.75 becomes "3.75". Without the .2, the default is six decimal places (e.g., "15.000000") — noisy for most purposes.

If you want to display the units (e.g., "square meters"), you could include them in the format string: printf("Area = %.2lf square meters\n", area);. This is more informative, but assumes the inputs were in meters. For a general-purpose program, leaving units off and relying on the user's interpretation is simpler, but for real applications, units should always be explicit.

8. The alternative: perimeter calculation

The variant adds perimeter = 2 * (length + width);. This uses two operators: + first (inside parentheses), then *. Without the parentheses, 2 * length + width would compute (2 * length) + width, which is wrong for perimeter. Parentheses matter.

Both area and perimeter are useful. Which one you compute depends on the application: painting a floor uses area; fencing a plot uses perimeter. Many real programs compute both and let the user choose.

9. Floating-point precision

Floating-point arithmetic is not exact — it uses binary fractions, which can't represent most decimal values exactly. For example, 0.1 in decimal is 0.0001100110011... in binary, repeating forever. So double x = 0.1; stores the closest representable value, which is off by about 10-17. For most practical purposes, this error is invisible, but it can accumulate over many operations or become visible when comparing values.

For area calculations with typical inputs, the precision is far more than enough. The comparison length <= 0 works correctly even with tiny floating-point errors (a value slightly off from 0 is still positive or negative in the expected direction). Only when comparing for exact equality (length == 0) would floating-point error be a concern — which is why you almost never compare floats with ==.

10. Handling invalid input more robustly

Our validation catches negative dimensions but not non-numeric input. If the user types "hello," scanf leaves length uninitialized and returns 0. The subsequent check might then read garbage (whatever was in that memory), which could be negative, positive, or zero — most likely positive by chance, in which case the program proceeds with nonsense.

The robust approach is to check scanf's return value:

if (scanf("%lf", &length) != 1) {
    printf("Error: invalid length input.\n");
    return 1;
}
                                

This catches cases where the input isn't a valid double. For a beginner program, it's often omitted; for production code, it's essential. The pattern generalizes: always check the return value of scanf, and handle failure gracefully.

🎯 Key idea: the area of a rectangle is one of the simplest calculations possible, but even here there are subtleties — type choice (double vs. int), input validation, and output formatting. Getting the simple programs right builds the habits you need for the complex ones. Master the basics; the advanced stuff follows naturally.

Frequently Asked Questions

1. Why use double instead of int for length and width?

Because dimensions can be fractional. If a user has a 2.5-meter by 4-meter room, the area is 10 square meters — but if length is int, scanf("%d", &length) with input "2.5" would read 2 and ignore the .5, giving the wrong area (8 instead of 10). double handles fractional dimensions naturally. Even if you expect whole-number inputs, using double costs nothing and protects against future changes.

2. What happens if the user enters a negative number?

Without the validation check, the program would compute and print a negative area, which is mathematically meaningless (you can't have negative square meters). With the check if (length <= 0 || width <= 0), the program prints an error and exits. Whether to include the check depends on the context — for a homework exercise, it may be optional; for real software, it's mandatory. Real users make real mistakes; the program should handle them gracefully.

3. Why does the program print "15.00" instead of "15"?

Because of %.2lf, which forces two decimal places even when the value is a whole number. This is a formatting choice — it makes the output look more like a proper measurement (15.00 square meters is clearer than 15 for a measurement). If you prefer "15", use %g (which drops trailing zeros), or print with %.0lf (which rounds to zero decimal places). The choice depends on the audience: scientific output often keeps decimals; casual output may prefer to drop them.

4. What if the user enters a very large number?

double can hold values up to about 1.8 × 10308, so for virtually any real-world dimension (even astronomical scales), there's no overflow. The result of length * width could overflow only if both dimensions exceed 10154, which is absurd for a rectangle. In practice, the range of double is far more than enough. The precision limit (~15 significant digits) is more relevant — multiplying two 20-digit numbers would lose precision — but again, this is far outside the range of realistic dimension values.

5. Can I use this program for a square?

Yes — a square is a rectangle where length equals width. If the user enters 5 for both, the area is 25, which is correct for a 5 × 5 square. The program doesn't need special handling for squares; the formula covers them automatically. If you wanted, you could add a check if (length == width) printf("(this is a square)\n"); — but it's not required. The formula is general.

6. How would I compute the volume of a rectangular box instead?

Read a third dimension, height, and compute volume = length * width * height;. The structure is identical: read inputs, multiply, print. The only change is one more variable and one more multiplication. This generalizes further: a 4D hyperrectangle's hypervolume is length * width * height * depth;, and so on. For higher-dimensional shapes, the pattern is always "multiply all the side lengths" — the concept of "area" generalizes to "n-dimensional measure."

💡 Tip: once this works, try the variant with perimeter. Then try a triangle area program: area = 0.5 * base * height;. The 0.5 (or / 2) is a nice reminder of floating-point division — and if you write / 2 with integer operands, you'll get integer division and the wrong answer. Same type-sensitivity lesson, different shape.

📖 Related Tutorials

  • Previous: Swap Two Variables Without a Third Variable
  • Next: Accept Employee Name and Salary and Display Them
  • Area of a Circle Using Single-Line Comments
  • Arithmetic Operators in C
  • Basic Input/Output Statements
  • Built-in Data Types in C
  • All 13 Introduction to C Assignments

Previous Topic: -->> 5. Swap Two Variables Without a Third Variable   ||   Next Topic: -->> 7. Accept Employee Name and Salary and Display Them


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.