C Program to Calculate Area of Rectangle Using Functions

1. Introduction

Functions in C programming provide modularity, which makes the code organized, manageable, and reusable. This tutorial will demonstrate how to use functions to calculate the area of a rectangle.

2. Program Overview

1. Define a function named calculateArea that will take the length and width of the rectangle as its parameters and will return the calculated area.

2. Inside the main function, declare variables for length, width, and area.

3. Prompt the user to enter the length and width of the rectangle.

4. Call the calculateArea function by passing the entered length and width, and store the result in the area variable.

5. Display the computed area of the rectangle.

3. Code Program

#include <stdio.h>

// Function to calculate the area of a rectangle
float calculateArea(float length, float width) {
    return length * width;  // return the product of length and width
}

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

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

    // Calculate the area
    area = calculateArea(length, width);

    // Display the area
    printf("The area of the rectangle is: %.2f\n", area);

    return 0;
}

Output:

Enter the length of the rectangle: 5
Enter the width of the rectangle: 3
The area of the rectangle is: 15.00

4. Step By Step Explanation

1. We have a function named calculateArea that accepts two parameters: length and width. This function computes the area of the rectangle by multiplying the length by the width and returns the result.

2. Inside the main function, we declare three float variables: length, width, and area.

3. We then prompt the user to input the length and width of the rectangle and store these values in the length and width variables respectively.

4. The function calculateArea is called by passing the entered length and width as arguments. The returned result (area of the rectangle) is stored in the area variable.

5. Finally, we display the computed area using printf.

Comments