Function Assignment 5 — Calculate the Area of a Rectangle Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Calculate the Area of a Rectangle Using a Function

📑 On this page:
  • The area formula, and why it needs a function
  • Designing the rectangleArea function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to write a function that returns a float instead of an int
  • How floating-point parameters work in function calls
  • How to format floating-point output with %.2f
  • Why the return type must match the arithmetic being performed
  • How to extend the same pattern to other shapes (triangle, circle, etc.)

The area formula, and why it needs a function

The area of a rectangle is length × width. That's it — one multiplication. So why write a function for it? Because in a real program, you rarely calculate the area of just one rectangle. You might be calculating it for dozens of rooms in a floor plan, hundreds of windows in a building, or thousands of tiles in a game map. Each time, you'd repeat the same multiplication, remembering to keep the units consistent and the variables straight. A function gives that multiplication a name — rectangleArea(length, width) — and that name documents the intent.

There's a subtler point too: the dimensions aren't always integers. A rectangle might be 5.5 units wide and 3.25 units long, giving an area of 17.875. If you wrote the multiplication in main using int variables, that 0.875 would be silently dropped — the result would be 17. Wrapping the calculation in a function whose parameters are float forces you to think about types, and forces the compiler to preserve the decimals. That's part of why functions matter: they create a contract about what types flow through the computation.

This assignment is the first one in the series where the function returns a float rather than an int. Everything up to now — sum, prime check, Fibonacci, even/odd — worked with integers. Floating-point arithmetic is where beginners start running into surprises (rounding, formatting, comparison). The rectangle area problem is small enough to see all the issues clearly, and central enough to be worth getting right.

💡 In one line: write a function float rectangleArea(float length, float width) that returns length * width. Read the dimensions as float, call the function, print the result with %.2f so the decimals are visible.

A rectangle with labelled length and width, showing how the area is length × width.

Designing the rectangleArea function

Three decisions, same as before — name, parameters, return type — but this time the types are float:

Part Choice Why
Function namerectangleAreaDescriptive — you know what it computes and for what shape. Not just area, because you'll likely add more shapes later.
Parametersfloat length, float widthDimensions can be fractional. Using int would truncate them and give wrong results for non-integer inputs.
Return typefloatThe product of two floats is a float. Returning int would round off the decimals.

That gives us the prototype:

float rectangleArea(float length, float width);
                                

And the definition:

float rectangleArea(float length, float width) {
    return length * width;
}
                                

Three lines — the same one-line body pattern as isEven and add. The function doesn't need any conditionals or edge-case handling in the body itself; the caller's job is to pass valid dimensions. If you want to guard against negative dimensions, that's a decision for main — the function's contract is "given two dimensions, return their product." Keeping the function pure like this makes it easy to test and reuse.

A subtle detail worth noticing: length * width is computed with float arithmetic because both operands are float. The result is a float, and it's returned as such. If you'd declared the return type as int but kept the multiplication in float, the return statement would silently truncate the result — 17.875 would come back as 17. That's a common bug, and it's why float in the return type matters.

🎯 Key idea: use float (or double) for both the parameters and the return type. If you mix — say, float parameters but an int return type — the return value gets truncated and the decimals silently disappear.

Complete C Program

Program: read length and width, call rectangleArea, print the result

#include <stdio.h>

/* Function prototype */
float rectangleArea(float length, float width);

int main(void) {
    float length, width, area;

    printf("Enter length and width of the rectangle: ");
    scanf("%f %f", &length, &width);

    area = rectangleArea(length, width);

    printf("Area of the rectangle: %.2f\n", area);

    return 0;
}

/* Function definition */
float rectangleArea(float length, float width) {
    return length * width;
}
                                    

And a version that reads integer dimensions from the user but still returns a float — useful when the inputs are whole numbers but you want to keep the return type consistent across the codebase:

Variant: integer inputs, float return

#include <stdio.h>

float rectangleArea(float length, float width) {
    return length * width;
}

int main(void) {
    int l, w;

    printf("Enter length and width (integers): ");
    scanf("%d %d", &l, &w);

    /* Implicit int-to-float conversion on each argument */
    printf("Area: %.2f\n", rectangleArea(l, w));

    return 0;
}
                                    

When you call rectangleArea(l, w) with int arguments, C automatically converts each int to float. This is a standard implicit conversion and works fine — you don't need explicit casts. The multiplication inside the function then happens in float arithmetic, and the result is a float. The only reason to prefer float inputs in main is if you want to support fractional dimensions; if the user might enter 5.5, you need float in main too.

Here's a third variant that extends the pattern to multiple shapes — a natural next step once you've got this working:

Variant: rectangle, triangle, circle in one program

#include <stdio.h>

float rectangleArea(float l, float w) { return l * w; }
float triangleArea(float base, float height) { return 0.5f * base * height; }
float circleArea(float radius) { return 3.14159f * radius * radius; }

int main(void) {
    printf("Rectangle 5.0 x 3.0  = %.2f\n", rectangleArea(5.0f, 3.0f));
    printf("Triangle  4.0 x 6.0  = %.2f\n", triangleArea(4.0f, 6.0f));
    printf("Circle    radius 2.5 = %.2f\n", circleArea(2.5f));

    return 0;
}
                                    

Three one-line functions, three different formulas. Once you've internalized the "prototype, definition, call" pattern, adding a new shape is a matter of writing one more function. This is exactly how calculators, CAD tools, and game engines are organized — a library of small, named, tested functions.

Program Output

A typical run with fractional inputs:

Enter length and width of the rectangle: 5.5 3.25
Area of the rectangle: 17.88
                                

With integer inputs:

Enter length and width of the rectangle: 10 4
Area of the rectangle: 40.00
                                

With a square (length equals width):

Enter length and width of the rectangle: 7 7
Area of the rectangle: 49.00
                                

And the multi-shape variant:

Rectangle 5.0 x 3.0  = 15.00
Triangle  4.0 x 6.0  = 12.00
Circle    radius 2.5 = 19.63
                                

Note the first output: 5.5 × 3.25 = 17.875, which prints as 17.88 due to rounding at two decimal places. The calculation itself is exact (to the limits of float precision); only the display is rounded. If you needed more precision, you'd use %.4f and get 17.8750. For money, you'd typically work in cents (integers) instead of dollars (floats) to avoid floating-point rounding altogether — but that's a topic for a different assignment.

Step-by-Step Explanation

Let's walk through the program and then look at why float is the right choice here.

1. The prototype

float rectangleArea(float length, float width); — same shape as before, but with float instead of int. The compiler now knows to expect two float arguments and to treat the return value as a float. This is critical: if the prototype says float but the definition accidentally says int, you get a link-time or compile-time error (or worse, silent truncation on some old compilers).

2. Reading inputs as floats

scanf("%f %f", &length, &width) — %f is the format specifier for float. If you used %d with float variables, scanf would misread the input and produce garbage. The & is essential — scanf needs addresses. This is the same pattern from earlier assignments, just with float instead of int.

3. The function call

area = rectangleArea(length, width); — the values of length and width are copied into the function's parameters (which happen to have the same names, but that's just a readability choice — the names inside the function are separate variables). The function multiplies them and returns the float product, which is assigned to area.

4. The multiplication

length * width — both operands are float, so the arithmetic is done in float precision. The result is a float. If one operand were int and the other float, the int would be promoted to float before the multiplication, and the result would still be float. In this case, both are float, so there's no promotion — just the multiplication.

5. The return

return length * width; — the computed float value is returned to the caller. No conversion is needed; the return type matches the expression type. If the function were declared to return int, the float would be truncated to an int before returning — losing the decimal part. That's the trap this design avoids.

6. Printing with %.2f

printf("Area of the rectangle: %.2f\n", area) — the %.2f specifier says "print as a floating-point number with exactly two digits after the decimal point." C rounds to two decimal places for display. Without the .2, the default is six decimal places, so you'd see 17.875000. For areas, two decimals is usually enough; for money, you'd use %.2f too; for scientific measurements, you might use %.6f or scientific notation (%e).

7. Why float and not int?

If dimensions were always whole numbers, int would be fine — and faster. But a rectangle in the real world can be 5.5 meters by 3.25 meters. If you used int, those inputs would be truncated to 5 and 3 (or rejected by scanf), and the result would be 15 instead of 17.875. Using float throughout preserves the fractional dimensions and the fractional area. It's a case where the choice of type is driven by the problem domain, not by what's convenient.

8. Why float and not double?

double has more precision (about 15–17 significant digits vs float's 6–7) and is the default floating-point type in C for historical reasons — a literal like 3.14 is a double unless suffixed with f. For rectangle areas in everyday units, float is plenty. But in code that mixes with double values or double literals, using double throughout avoids conversion warnings and minor precision surprises. It's a stylistic choice — float is fine for this program, double is fine too, and switching is a one-word change in three places (prototype, definition, variable declarations).

9. Precision and rounding — the honest picture

Floating-point numbers in C can't represent every decimal exactly. 0.1 in binary floating-point isn't exactly 0.1 — it's a value very close to it. For rectangle areas, the errors are in the seventh or eighth significant digit, far below what you'd display. But if you compare areas for equality, or accumulate many small areas, the errors can add up. For simple one-shot calculations like this, you don't need to worry. For financial calculations or scientific simulations, you'd use double or specialized decimal types.

🔍 Try this: change the return type to int (both in the prototype and definition) and run with 5.5 3.25. The output becomes 17.00 instead of 17.88 — the decimals are lost. This is the most direct demonstration of why the return type matters. Revert the change afterwards.

Frequently Asked Questions

1. What if the user enters a negative dimension?

The function will happily compute a positive area from two negatives, or a negative area from one — mathematically wrong, but the function itself isn't responsible for validation. The right place to reject negative dimensions is main, before calling rectangleArea. For example: if (length <= 0 || width <= 0) { printf("Dimensions must be positive\n"); return 1; }. This separation of concerns — validation in the caller, calculation in the function — is a good habit to build early.

2. Should I use float or double?

For this program, either works. float saves a few bytes per value and is fine for typical dimensions. double is more precise and is the default for floating-point literals — 3.14 is a double, so if you're mixing literals with variables, double avoids implicit conversions. Most modern code uses double as the default and reserves float for memory-constrained contexts (embedded systems, large arrays in games). If you switch to double, change the format specifier in scanf and printf from %f to %lf in scanf (though %f still works in printf for double, the printf specifier convention is %f for both).

3. Why does 5.5 × 3.25 = 17.875 print as 17.88?

Because %.2f rounds to two decimal places. The internal value is 17.875 (or very close to it, given floating-point representation), but display rounds it to the nearest hundredth. To see more digits, use %.4f (four decimals) or %.6f (six decimals). The underlying precision is there — only the display is being trimmed.

4. Can I use the same function to compute the area of a square?

Yes — call rectangleArea(side, side). A square is just a rectangle with equal length and width. No separate function needed. The multi-shape variant above does this directly: rectangleArea(7, 7) gives 49. If you really want a dedicated square function, it's a one-liner: float squareArea(float side) { return side * side; } — but the rectangle version handles it for free.

5. Why not just write the multiplication in main?

You could — it's one line either way. But a function gives you: (a) a name that documents intent (rectangleArea(l, w) is clearer than l * w, especially if the formula changes), (b) a single place to fix if the formula turns out wrong, (c) an easy way to test the calculation in isolation, and (d) consistency with the rest of the codebase. The cost is a tiny bit of overhead at runtime (negligible for this function), and the benefit is maintainability. For very simple programs, direct multiplication is fine; once you start writing more than a handful of these, functions pay off.

6. What happens if I use %d instead of %f in scanf?

Undefined behavior. scanf("%d", &length) where length is float tells scanf to read an int and store it in a float's memory. The byte layout is different (typically 4 bytes either way, but the bit interpretation is completely different), so the value stored in length is garbage. Similarly, using %d in printf with a float argument produces undefined output. Always match the format specifier to the type: %f for float, %lf for double in scanf, %f or %lf in printf for both.

💡 Tip: Once this works, add a perimeter function — float rectanglePerimeter(float l, float w) { return 2 * (l + w); }. Then build a tiny "shape calculator" that asks the user for a shape (rectangle, triangle, circle) and prints both area and perimeter. Each shape is two functions. The pattern scales naturally, and you'll see why naming functions after what they compute — not after how they compute it — matters.

📖 Related Tutorials

  • Introduction to Functions in C
  • Need for User-Defined Functions
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Built-in Data Types
  • Basic Input/Output
  • All 33 Function Assignments

Previous Topic: -->> 4. Check Whether a Number Is Even or Odd Using a Function   ||   Next Topic: -->> 6. Convert Temperature from Celsius to Fahrenheit Using a Function


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.