Make a function called minmax. It has five numbers as parameters. first three parameters are input numbers call by value. 4th parameter is a reference parameter callled "minimum" and fifth parameter is a reference parameter called "maximum". The function should find the minimum and maximum and return the values.
My code works fine. But i don't understand the real purpose of reference parameters.
if I use int minimum and int maximum as function parameters instead of int& code runs giving wrong output.
Please tell me the real purpose of reference parameters
#include <iostream>
using namespace std;
void minmax( int a , int b, int c, int& minimum, int& maximum){
cout<< "PLEASE ENTER FIRST VALUE";
cin>> a;
cout<< "PLEASE ENTER SECOND VALUE";
cin>> b;
cout<< "PLEASE ENTER THIRD VALUE";
cin >> c;
if (a > b and a>c){
maximum= a;
}else if( b>a and b>c){
maximum =b;
}else if(c>a and c>b){
maximum = c;
}
if(a< b and a < c){
minimum = a;
}else if (b<a and b<c){
minimum = b;
}else if(c<a and c<b){
minimum = c;
}
}
int main(int argc, char** argv) {
int a ; int b; int c; int minimum; int maximum;
minmax(a,b,c,minimum,maximum);
cout<< "minimum value is " << minimum << "\n"<< endl;
cout<< "maximum value is " << maximum << "\n"<< endl;
return 0;
}
Simply said, when you pass in a reference parameter into a function, and the function changes its value, then the original variable you passed into the function gets changed too.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
void foo(int &x)
{
x = 5;
}
int main()
{
int x = 4;
std::cout << x << std::endl; //prints 4
foo(x);
std::cout << x << std::endl; //prints 5, as the call to foo has changed the value of x
return 0;
}
Also, instead of a chain of if-statements, you can simplify your code:
1 2 3 4 5 6 7
int min(int a, int b) { return a < b? a: b; }
int max(int a, int b) { return a > b? a: b; }
void minmax(int a, int b, int c, int& minimum, int& maximum) {
minimum = min(a, min(b, c));
maximum = max(a, max(b, c));
}