Function returning multiple values
- Anonymous
- Aug 5, 2015
- 1 min read
Usually a function can return only a single value through 'return' keyword. We intend to design a function that returns multiple values with no 'return' keyword used in whole funcion's definition.
Q.Design a maths() function that takes two integer inputs and returns their sum, difference and product (Mind Its! It returns three values, does not print them in its definition.). Later on you print these returned values in main(). But do not use any printing statement in definition of math() function.
Sample Input:
Enter two values..4 2
Sample output:
Sum = 6
Dif = 2
Product = 8
Solution:
Concept is if we use a pointer variable to point to an integer and pass it's value by reference(using addressOf operator) then if we make any changes to pointer variable then value is changed at its actual address rather than changing value of it's copy.
Code:
#include <iostream>
using namespace std;
void maths(int,int,int*,int*,int*); // prototype
int main()
{
cout << "Enter two values..";
int a,b,s,d,p;
cin >> a >> b;
maths(a,b,&s,&d,&p); // passing variable by reference
cout << "Sum = " << s << endl << "Dif = " << d << endl << "Product = " << p;
return 0;
}
void maths(int a,int b,int *sum,int *dif,int *prod)
{
*sum = a+b; // changing value of sum at its location in memory
*dif = a-b;
*prod = a*b;
}
Comments