Topic 8: Functions (Pass by value)

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:

  • Built-in Functions: Pre-defined functions provided by libraries like pow and sqrt.
  • User-Defined Functions: Functions defined by programmers to perform specific tasks.

Built-in Functions

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:

Example 1: Calculating 2^3
  • cout << pow(2.0, 3);
Example 2: Calculating square root of 100
  • cout << sqrt(100.0);

User-Defined Functions

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 Syntax
Figure 8.1: Function 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.

Calling a Function

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);

  • argumentList contains actual arguments (if any).
  • An actual argument can be a variable, named constant, literal constant, or keyword.

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.

Function Prototypes

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);

Example 1: Function Prototype with Named Parameters
  • double calculatePay(double hoursWorked, double rate);
Example 2: Function Prototype with Unnamed Parameters
  • double calculatePay(double, double);

Void Functions

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:
  1. void functionName([parameterList])
  2. {
  3. statement;
  4. }
Example: To call the following function simply say displayCompanyInfo();
    1. void displayCompanyInfo()
    2. {
    3. cout << “XYZ Company Ltd” << endl;
    4. cout << “Fiji Islands” << endl;
    5. }

Practice Questions

  1. What does it mean to pass an argument by value in a function?
  2. WWhat are the key advantages of passing parameters by value?
  3. What are the advantages of using constants in a program? List at least three.
  4. In C++, what happens to the local copy of the argument passed by value after the function completes execution?
  1. Write a C++ function add(int a, int b) that takes two integer arguments and returns their sum. Call this function from main()and display the result.
    • Pass the two integers by value to the add() function.
    • Ensure that changes to the parameters inside the function do not affect the values in main().
  2. Create a function swap(int a, int b) that swaps two integers and prints the swapped values inside the function.
    • Pass the integers by value.
    • Print the swapped values inside the swap() function.
    • In main(), print the original values to show that they remain unchanged.
  3. Write a function square(int x) that returns the square of an integer passed by value.
    • Create a function that takes an integer argument by value.
    • Inside the function, calculate and return the square of the integer.
    • In main(), call the function and print the squared value.
  4. Write a function isEven(int num) that takes an integer by value and returns true if the number is even, and false if the number is odd. Then displays where a number is odd or even.
    • Create the isEven() function to check if the number is divisible by 2.
    • In main(), prompt the user for an input, pass it by value to the function, and print the result.
  5. Create a function 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.
    • Pass two integers by value to the function.
    • Use an if-else statement inside the function to determine the larger number.
    • Print the result in main().
  6. Write a function 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.
    • Define the function with the formula for simple interest.
    • Call the function from main() and pass appropriate values by value.
    • Print the calculated interest.
    • Test your program with values p = 1000, i = 5, t = 2. The simple interest should be 100
  7. Write a function convertToFahrenheit(float celsius) that takes a temperature in Celsius by value and converts it to Fahrenheit using the formula Fahrenheit = (Celsius * 9/5) + 32.
    • Pass the Celsius temperature by value to the function.
    • Convert the value to Fahrenheit and return it.
    • Print the converted temperature in main().
  8. The volume of a cylinder is given by this formula: V = ∏r2L where r is the cylinder’s radius and Lis its length. Using this formula, write a function named calculateVol() that calculates the volume.
    • The user should enter radius and length
    • The function calculateVol() calculates and returns the volume
    • Display the volume in main()
  9. Write a function 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.
    • Pass the integer nby value.
    • Calculate the factorial inside the function using a loop.
    • Return and print the result in main().
  10. Write a function isPrime(int n) that takes an integer by value and returns true if the number is prime, and false otherwise.
    • Pass an integer by value.
    • Implement a loop to check if the number is prime.
    • Print the result in main().
  11. Write a function sumOfDigits(int n)s that takes an integer by value and returns the sum of its digits.
    • Pass the integer by value.
    • Use a loop to calculate the sum of its digits.
    • Return and print the sum in main().
    • Example: The sum of 1234 is 10.
  12. Write a program in C++ using functions that enable the clerk to calculate employee gross pay based on the hours worked by its employees. The program has the following functions:
    1. double getHoursWorked(): returns the number of hours worked by the employee entered by the clerk.
    2. double getPayRate(): returns the pay rate for its employee entered by the clerk
    3. double calcGross(double hours: double rate); returns the gross pay which is calculated by multiplying hours and rate.

    • Write the main program for the program that will call the functions to calculate the gross pay. Declare appropriate variables in use and use the correct method of calling functions.
    • Modify the above main program using a while loop so that the program repeats itself until the hours worked entered is a negative number
Coming Soon...