-
Notifications
You must be signed in to change notification settings - Fork 142
Functions
Functions are essential in C++ because they can be used for repetitive tasks and to simplify code. For example,
#include <iostream>
using namespace std;
double power(double, int);
int main()
{
int exponent=18;
double base=5.3;
double value;
value = power(base,exponent);
cout.precision(12);
cout << value << endl;
return 0;
}
double power(double a, int n)
{
int i;
double val=a;
for(i=1; i < n; i++)
val *= a;
return val;
}
The function power() calculates the value of {\rm base}^{\rm exponent}, and is defined explicitly in the code segment following main(). The function takes two arguments, a double and an int (in that order), and it returns a double, which main() prints to stdout. Some points to note:
Above the code for main() we find the “declaration” of the power() function, including the types of its arguments and return value. This declaration is necessary so that the compiler can make sure that the use of power() remains consistent throughout the code. (Think of the compiler as reading the source code blindly from top to bottom.) Note that the names of the variables passed to power() by main() do not match (a and n vs. base and exponent). This is an example of variable scope. The cout.precision(12) directive tells the output stream to include 12 significant figures when printing the numerical value.