A function is a block of code grouped with a name and performs a task. Every C++ program contains at least one function i.e. the main function. Some functions are built-in functions, defined in libraries e.g., pow, sqrt, time etc. Others, called program-defined functions, are written by programmers.
Functions allow for blocks of code to be used many times in a program without having to duplicate code. They also allow large, complex programs to be broken down into small, manageable sub-tasks. Each sub-task is solved by a function, allowing different people to write different functions.
Many functions can then be combined into a single program. Typically, the main function calls other functions, but any function can call any other function.
There are two types of functions:
pow
and sqrt
.
The pow function is used to raise a number to a power (exponentiation). Its syntax is pow(x, y), where x is the base and y is the exponent. At least one of the two arguments must be a double.
The sqrt function returns a number’s square root as a double. Its syntax is sqrt(x), where x is a double or float.
These functions are defined in the cmath library, so your program must include the directive
#include
Examples of built-in functions:
cout << pow(2.0, 3);
cout << sqrt(100.0);
A program-defined value-returning function definition consists of a header and a body. The header (first line) includes the return data type, function name, and an optional parameter list.
Syntax:
Function names follow the same rules as variables. It’s advisable to use meaningful names that describe the function’s purpose, preferably verbs.
The memory locations in the parameter list are called formal parameters, each storing an item of information passed to the function when it’s called.
The function body contains instructions for performing the function’s assigned task, enclosed in braces ({}). The last statement is typically the return statement, which returns one value (matching the return data type in the function header).
Functions can be called from the main
function or other functions.
A function must be called (invoked) to perform its task. The main function is automatically called when the program runs, while other functions must be called by a statement.
Syntax:functionName(argumentList);
C++ allows passing either a variable’s value or its address to a function. Passing a variable’s value is passing by value, while passing its address is passing by reference. The choice depends on whether the receiving function needs to modify the variable’s contents.
Passing by value will not permit the function to change the contents of the variable, but passing by reference will. Passing a variable by value means that only a copy of the variable’s contents is passed, not the address of the variable. This means that the receiving function cannot change the contents of the variable
The number, data type, and ordering of actual arguments must match the formal parameters in the function header.When a function definition appears below the main function, a function prototype must be written above the main. It specifies the function’s name, return value data type, and each formal parameter’s data type (if any). Formal parameter names in the prototype are optional.
Syntax: returnDataType functionName(parameterList);
double calculatePay(double hoursWorked, double rate);
double calculatePay(double, double);
Void functions perform tasks like value-returning functions but do not return a value. The function header starts with the void keyword instead of a return data type. The function body does not include a return statement. Call a void function with its name and actual arguments (if any) in a statement.
Syntax:
- void functionName([parameterList])
- {
- statement;
- }
- void displayCompanyInfo()
- {
- cout << “XYZ Company Ltd” << endl;
- cout << “Fiji Islands” << endl;
- }
add(int a, int b)
that takes two integer
arguments and returns their sum. Call this function from main()
and
display the result.
add()
function.main()
.swap(int a, int b)
that swaps two integers and
prints the swapped values inside the function.
swap()
function.main()
, print the original values to show that they
remain unchanged.square(int x)
that returns the square of an
integer passed by value.
main()
, call the function and print the squared value.
isEven()
function to check if the number is
divisible by 2.main()
, prompt the user for an input, pass it by value
to the function, and print the result.findMax(int a, int b)
that takes two integers by
value and returns the greater of the two numbers. Use an
if-else
statement inside the function to determine the larger
number.
if-else
statement inside the function to determine
the larger number.calculateInterest(float principal, float rate, int time)
that
calculates the simple interest based on the formula Interest = (Principal * Rate *
Time) / 100
. The function should take all values by value.
convertToFahrenheit(float celsius)
that takes a
temperature in Celsius by value and converts it to Fahrenheit using the formula
Fahrenheit = (Celsius * 9/5) + 32
.
main()
.V = ∏r2L
where r
is the
cylinder’s radius and L
is its length. Using this formula, write a
function named calculateVol()
that calculates the volume.
calculateVol()
calculates and returns the
volumemain()
factorial(int n)
that takes an integer n by value
and returns the factorial of n
. Factorial is calculated as
n! = n * (n-1) * (n-2) * ... * 1
.
n
by value.main()
.main()
.sumOfDigits(int n)
s that takes an integer by value
and returns the sum of its digits.
main()
.double getHoursWorked()
: returns the number of hours worked
by the employee entered
by the clerk.double getPayRate()
: returns the pay rate for its employee
entered by the clerkdouble calcGross(double hours
: double rate); returns the
gross pay which is calculated
by multiplying hours and rate.