Doing the mathematical arithmetic operation to demonstrate the user defined functions in C++ programming
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Doing the mathematical arithmetic operation to demonstrate the user defined functions in C++ programming
To show: How to declare, define and use the user defined functions in C++ programming
// user defined function and header file. A very simple arithmetic functions
#include <iostream>
using namespace std;
// function prototypes
float AddNum(float, float);
float SubtractNum(float, float);
float DivideNum(float, float);
float MultiplyNum(float, float);
void main(void)
{
// local (to this file) scope variables
float p, q, r, s, t, u;
// prompting for user inputs
cout<<"Enter two numbers separated by space: "<<endl>>p>>q;
// function calls
r = AddNum(p, q);
s = SubtractNum(p, q);
t = DivideNum(p, q);
u = MultiplyNum(p, q);
// display the result and quit
cout<<"\nAddition: "<<p <<" + "<<q<<" = "<<r<<endl;
cout<<"Subtraction: "<<p <<" - "<<q<<" = "<<s<<endl;
cout<<"Division: "<<p <<" / "<<q<<" = "<<t<<endl;
cout<<"Multiplication: "<<p <<" * "<<q<<" = "<<u<<endl;
return;
}
// function definitions part
float AddNum(float p, float q)
{
cout<<"In AddNum(), a + b...\n";
return (p + q);
}
float SubtractNum(float p, float q)
{
cout<<"In SubtractNum(), a - b...\n";
return (p - q);
}
float DivideNum(float p, float q)
{
cout<<"In DivideNum(), a / b...\n";
// do some checking here to avoid divide by 0
if (q == 0)
{
cout<<"Divide by 0 detected\n";
return 0;
}
else
return (p / q);
}
float MultiplyNum(float p, float q)
{
cout<<"In MultiplyNum(), a * b...\n";
return (p * q);
}
Output example:
Enter two numbers separated by space:
5 10
In AddNum(), a + b...
In SubtractNum(), a - b...
In DivideNum(), a / b...
In MultiplyNum(), a * b...
Addition: 5 + 10 = 15
Subtraction: 5 - 10 = -5
Division: 5 / 10 = 0.5
Multiplication: 5 * 10 = 50
Press any key to continue . . .