A Function returning more than one value

Using call by reference method we can make a function return more than one value at a time, which is not possible in the call by value method. The following program will make you the concept very clear.

Write a program to find the perimeter and area of a rectangle, if length and breadth are given by the user.

/* Program to find the perimeter and area of a rectangle*/
#include <stdio.h>
void main()
{
float len,br;
float peri, ar;
void periarea(float length, float breadth, float *, float *);
printf("\nEnter the length and breadth of a rectangle in metres: \n");
scanf("%f %f",&len,&br);
periarea(len,br,&peri,&ar);
printf("\nPerimeter of the rectangle is %f metres", peri);
printf("\nArea of the rectangle is %f sq. metres", ar);
}
void periarea(float length, float breadth, float *perimeter, float *area)
{
*perimeter = 2 * (length +breadth);
*area = length * breadth;
}

OUTPUT

Enter the length and breadth of a rectangle in metres:
23.0 3.0
Perimeter of the rectangle is 52.000000 metres
Area of the rectangle is 69.000000 sq. metres

Here in the above program, we have seen that the function periarea is returning two values. We are passing the values of len and br but, addresses of peri and ar. As we are passing the addresses of peri and ar, any change that we make in values stored at addresses contained in the variables *perimeter and *area, would make the change effective even in main() also.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: