Introduction
In this lab, you will learn how to calculate the area of a rectangle using a user-defined function in the C programming language.
In this lab, you will learn how to calculate the area of a rectangle using a user-defined function in the C programming language.
In this lab, you will learn how to find out the area of a rectangle using a function.
Create a new file named rectangle.c
in WebIDE.
Add the following code to the rectangle.c
file:
#include <stdio.h>
int area(int h, int w)
{
int area = h * w;
return area;
}
void main()
{
int height, width;
printf("Enter the height of the rectangle: ");
scanf("%d", &height);
printf("Enter the width of the rectangle: ");
scanf("%d", &width);
printf("The area of the rectangle = %d\n\n\n", area(height, width));
}
This code defines a function area
that takes two parameters h
and w
representing the height and width of the rectangle, respectively. The function calculates the area of the rectangle by multiplying the height and width and returns the result.
The main
function reads the height and width values from the user, calls the area
function to calculate the area, and then prints the result.
Save the rectangle.c
file.
Open a terminal and navigate to the directory where the rectangle.c
file is located.
Compile the rectangle.c
file using the following command:
gcc rectangle.c -o rectangle
This command compiles the C code and generates an executable file named rectangle
.
Run the rectangle
executable using the following command:
./rectangle
When prompted, enter the height and width of the rectangle.
The program will calculate and print the area of the rectangle.
After completing this lab, you will be able to calculate the area of a rectangle using a user-defined function in the C programming language.