3. Functions

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial


Overview

Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Arrays

  1. Every C++ function comprises at least one function
    • main()
  2. You can also split functionality into multiple functions
    • Aids modularity
    • Each function has a specific purpose
  3. C++ allows global functions
    • But OO dictates that most functions should be defined in classes – these are known as methods”
    • We’ll discuss this in the “Defining and Using Classes” chapter

Lab 1: Defining and calling functions

Lab 1: Defining and calling functions
  1. Declaring Function Prototypes
    • There’s a key rule in C++:
      • You must declare an item before you can use it
      • i.e. the compiler has to know what you’re talking about
    • This is relevant for functions
      • You have to declare what a function looks like, before you call it
      • Function declarations are also known as “function prototypes”
    • A function prototype specifies:
      • The name of a function, its parameter types, and its return type
    • It’s common to place function prototypes in a header file
      • You can #include the header file in any source file it’s needed
    • Here’s an example of a header file that declares several function prototypes
      • Note: parameter names are optional (but desirable) in a prototype
        void displayWelcome();
        int calcSum(int a, int b);
        bool isValidMonth(int m);
    • To include a header file in another source file, there are 2 possible syntaxes:
      #include <iostream> //Standard header files, located in the compiler system folder
      #include "MyHeader.h" //User-defined header files, located in your own folder
  2. Defining Function Bodies
    • A function body contains the code for a function
      • Also known as a function definition”
      • Place function definitions in a source file (.cpp)
      • Also #include the header file, to ensure the function signature matches what you promised in the prototype
        #include <iostream>
        #include "MyHeader.h"
        using namespace std;
        void displayWelcome()
        {
         cout << "Hello mate!" << endl; }  int calcSum(int a, int b) {  return a + b; } bool isValidMonth(int m) {  return (m >= 1) && (m <= 12); }
  3. Calling Functions
    • To call a function:
      • Specify the function name
      • Pass any parameter values needed by the function
      • Use the return value, if there is one (and if you want to)
    • Functions

    • Simple client code:
      #include <l;iostream>
      #include "MyHeader.h"
      using namespace std;
      int main()
      {
       displayWelcome();
       int sum = calcSum(10, 20);
       cout << "Sum is " << sum;  bool flag = isValidMonth(12);  cout << "Is month valid? " << flag;  return 0; }
    • Here's another client example
      • Shows how to use variables, rather than constants
      • Shows how to use function return values in-situ
        #include <iostream>
        #include "MyHeader.h"
        using namespace std;
        int main()
        {
         int num1, num2;
         cout << "Enter two numbers: ";  cin >> num1 >> num2;
         cout << "Sum is " << calcSum(num1, num2) << endl;  int month;  cout << "Enter a month number: ";  cin >> month;
         if (isValidMonth(month))
          cout << "Month is valid" << endl;  else   cout << "Month is invalid" << endl;  return 0; }
  4. Pass-By-Value
    • By default, functions always take a copy of the value passed in from the client
      • Except for arrays, which are passed by address (see later)
      • For other types, you can use pointers or references if you want the function to work on the original value (see later)
    • Example of pass-by-value:
      int n = 10;
      cout << "Here are 5 numbers, starting at " << n << endl; displayNumberRange(n, 5); cout << "Did you notice the first number was " << n << endl // FUNCTION void displayNumberRange(int num, int count) {  int lastNum = num + count;  while (num < lastNum)   cout << num++ << endl; }
Lab
  1. Determining whether a number is prime
    • Start Visual Studio, and create a new C++ project named MathApp in the student folder. Write a function named IsPrime(). The function needs to take an integer parameter and return a boolean, to indicate whether the number is prime (a number is prime if it has no other factors than 1 and itself).
      bool IsPrime(int number)
      {
       for (int i=2; i < number; i++)  {   if (number % i == 0)   {    return false;   }  }  return true; }
    • View code file.
    • In main(), ask the user to enter a number, and pass it into your IsPrime() function to determine if it's a prime number. Display a result message in main().
       cout << "Enter a number: ";  int number;  cin >> number;
       if (IsPrime(number))
       {
        cout << number << " is prime." << endl;  }  else  {   cout << number << " is not prime." << endl;  }
    • View code file.

Lab 2: Additional techniques

Lab 2: Additional techniques
  1. Default Arguments
    • You can define default arguments in function prototypes
      • Use = to define a default argument
      • Can be used only for right-most arguments
    • Example:
      // header
      void displayArithmeticProgression(int startNum, int count, int delta = 1);
      void bookHotelRoom(int numAdults = 1, int numChildren = 0);
      void displayWelcome(string language = "English");
      // cpp file
      displayArithmeticProgression(10, 5, 2); // Passes 10, 5, 2.
      displayArithmeticProgression(10, 5); // Passes 10, 5, 1.
      bookHotelRoom(2, 2); // Passes 2, 2.
      bookHotelRoom(2); // Passes 2, 0.
      bookHotelRoom(); // Passes 1, 0.
      displayWelcome("Welsh"); // Passes "Welsh".
      displayWelcome(); // Passes "English".
  2. Function Overloading
    • You can define overloaded functions
      • Multiple functions with the same name, but different parameters
      • Either the number or type of parameters must be different (the return type is insignificant)
      • Compiler resolves calls based on the actual parameters passed in
    • Example:
      // Header
      double calcInterest(int dollars, int cents);
      double calcInterest(double amount);
      double calcInterest(string amountStr);
      // Cpp File
      cout << calcInterest(1000, 99) << endl; cout << calcInterest(1000.99) << endl; cout << calcInterest("1000.99") << endl;
  3. Header Guards
    • It's conventional to wrap the innards of a header file in a "header guard"
      • Enables the compiler to detect whether the same header file has been included several times whilst compiling a given .cpp file
      • Prevents declarations from being parsed multiple times during a "compilation unit" (i.e. whilst compiling a given .cpp file)
    • Here's the traditional way to define a header guard:
      #if !defined __BANKACCOUNT_HEADER__
      #define __BANKACCOUNT_HEADER__
      // BankAccount declarations, e.g. function prototypes, structures, classes, etc.
      #endif
Lab
  1. Finding all prime numbers in a range
    • Write a function named DisplayPrimeNumbersInRange(). The function should take 2 integer parameters (representing lower and upper bounds), and return nothing. The function should display all the prime numbers in the range (lowerBound...upperBound-1). Note, it's quite common for the lower bound to be inclusive, but the upper bound exclusive.
      void DisplayPrimeNumbersInRange(int lower, int upper)
      {
       cout << "The following numbers between " << lower << " and " << upper << " are prime" << endl;  for (int i = lower; i < upper; i++)  {   if (IsPrime(i))   {    cout << i << endl;   }  } }
    • View code file.
    • In main(), ask the user to enter the lower and upper bounds, and then call your function.
       cout << endl << "Enter a lower number: ";  int lower;  cin >> lower;
       cout << "Enter an upper number: ";  int upper;  cin >> upper;
       DisplayPrimeNumbersInRange(lower, upper);
    • View code file.

 

Well done. You have completed the tutorial in the C++ course. The next tutorial is

4. Arrays


Back to beginning
Copyright © 2016 TalkIT®





If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top