C program that returns more than one value from function

      Actually, Functions in C programming can return only one value but to get more than one value from the function one has to use pointers. A pointer is a variable which stores the address of another variable. So whenever a pointer is taken as function argument it will store the address of the variable. So any modifications done on the variable in the function will be reflected on the actual value and the modified value can be accessed again in the main block. This way indirectly one can return more than one value from the function using pointers.

c program that return more than one value from a function



Source Code :

#include<stdio.h>;
int main()
{
//return more than one value
   float r, area, perimeter;
   float compute(float,float*);           // Step 1
   printf("\n enter the radius of the circle:");
   scanf("%f",&r); //Step 2
   area=compute(r, &perimeter); //Step 3
   printf("\n AREA = %f", area);      //Step 5
   printf("\n PERIMETER = %f", perimeter); //Step 5
   return 0;
}
float compute(float r, float *p)
{
   float a;
   a=(float)3.1415 * r * r;  //Step 4
   *p=(float)3.1415 * 2 * r; //Step 4
   return a;
}


edit-code-image

Sample Test cases :

1.  enter the radius of the circle: 2
    AREA = 12.566000
    PERIMETER = 12.566000

2.  enter the radius of the circle:3.14
    AREA = 30.973936
    PERIMETER = 19.728621 

Explanation for function that return more than one value:

Step 1: The function compute(float, float*) prototype is specified which takes radius and perimeter as arguments.

Step 2: The radius is read from the user using scanf() function.

Step 3: The compute() function is called from the main program.

Step 4: The compute function computes the value of area and perimeter and returns the value of area directly. The perimeter value gets updated and can be accessed in the main block as it is a pointer variable.

Step 5: After return from the function the values of area and perimeter are printed on the output screen using printf() function.

More Insights:

More Information
Explore C Programs:C Programs