Function that returns a value
A function that is declared with a data
type other than void returns a value.
Syntax:
Datatype functionname()
{
//body
of a function with return value.
}
The returned value of a function
depends on the data type. For example, if a function is declared with a numeric
data type, therefore the returned value must also be a numeric type.
Sample Program: Calculator using
function that returns a value
#include<iostream>
using namespace std;
float sum()
{
float
s,a,b;
cout<<"First
Number: ";
cin>>a;
cout<<"First
Number: ";
cin>>b;
s
= a + b;
return
s;
}
float difference()
{
float
a,b;
cout<<"First
Number: ";
cin>>a;
cout<<"First
Number: ";
cin>>b;
return
(a-b);
}
float product()
{
float
a,b;
cout<<"First
Number: ";
cin>>a;
cout<<"First
Number: ";
cin>>b;
return
(a*b);
}
float quotient()
{
float
a,b;
cout<<"First
Number: ";
cin>>a;
cout<<"First
Number: ";
cin>>b;
return
(a-b);
}
int remainder()
{
int
a,b;
cout<<"First
Number: ";
cin>>a;
cout<<"First
Number: ";
cin>>b;
return
(a%b);
}
int main()
{
char opt;
cout<<"Choose
your option: "<<endl
<<"\t<S>um"<<endl
<<"\t<D>ifference"<<endl
<<"\t<P>roduct"<<endl
<<"\t<Q>uotient"<<endl
<<"\t<R>emainder"<<endl
<<"Option
-> ";
cin>>opt;
switch(opt)
{
case
's':
case 'S': cout<<"The sum is: "<<sum()<<endl;
break;
case 'd':
case 'D': cout<<"The difference is:
"<<difference()<<endl;
break;
case 'p':
case 'P': cout<<"The product is:
"<<product()<<endl;
break;
case 'q':
case 'Q': cout<<"The quotient is: "<<quotient()<<endl;
break;
case 'r':
case 'R': cout<<"The remainder is:
"<<remainder()<<endl;
break;
default:
cout<<"Invalid input!"<<endl;
system("pause");
return 0;
break;
}
system("pause");
return 0;
}
The sample program, though has a lot of redundancy, shows how the function that returns a value works.
ReplyDeleteIf you notice that in function sum(), before returning the value, it was assigned first to a variable. This sometimes necessary to simplify the returned value. And on the rest of the function, difference(), product(), quotient(), and remainder(), the return value is the expression itself. This is valid just make sure not to confuse yourself and the program. Just group the expression using the open and close parenthesis().