Lesson # 2. C++ Methods / Functions. Multi-file layout

Theory

Standard functions

The math functions are declared in the <cmath> header file:

#include <cmath>
abs(x);  
floor(x);  
sin(x);  
pow(x, y);  
sqrt(x);

User functions

sample 1:

//...
int abs(int x) {
	return x > 0 ? x : -x;  // exit the function
}
int main() {
	cout << abs(-35); // 35
	system("pause");
	return 0;
}

The abs function returns integer value and have got single integer x parameter.

sample 2:

//...
void print(int i) {
	cout << "value = " << i;
}
int main() {
	print(40);
	system("pause");
	return 0;
}

The print function returns no value and have got single integer i parameter. We can call it procedure (because it doesn’t return value).

Encapsulation

In C++, data and functionality are separated into two separate protections: public and private.
The protection level determines the access that “client code” has to the member data or functionality:

  • Public members can be accessed by client code.
  • Private members cannot be accessed by client code (only used within the functions themselves).

In C++, the interface (.h file) to the function is defined separately from the implementation (.cpp file).

Multi-file layout

To make an application, you usually need to create 3 files: header file (.h), implementation file (.cpp), and main file (.cpp).

  • A header file (.h) defines the interface to functions, that is declaration(s) of the function(s)
  • Implementation .cpp file contains all of the logic of the functions or methods. Header .h file must be included here.
  • Main .cpp file contains of the main function, the starting point of all C++ programs, and here header .h file also need to be included.

Let’s look at the example of 3 files of single application.
Sample header file (tasks.h):

#ifndef TASKS_H
#define TASKS_H
//calculates a triangle perimeter 
double perimeter(double, double, double);
#endif TASKS_H

Sample implementation file (.cpp):

#include "tasks.h"
//calculates a triangle perimeter 
double perimeter(double a, double b, double c)
{
	//TODO
}

Sample main file (.cpp):

#include <iostream>
#include "tasks.h"
using namespace std;
void main()
{
	//prompt user to enter data 
	//call the function
	//print out the result
	system("pause");
}
  • The.cpp files make requests to include various header files.
  • Then, the cpp file with all of its extra included content will be compiled into object file. (a file has a .o extension, that is an object file.) Each cpp file is separately compiled into an object file.
  • Labs and Tasks

    All the tasks that you did not have time to complete in class automatically become your homework. The homework must be completed before the next lesson.
    Lab 1:

    To do: Create an application to find the volume and surface area of a cube. The length of the cube side is given (it is entered).
    Note: Three solutions must be presented: 1) Without using functions and multi-file application, 2) Using functions, 3) Creating a multi-file application.

    Expected output:

    Please enter the cube side length: 3.48
    Volume: 42.1442
    Surface area: 72.6624

    [Solution and Project name: Lesson_2Lab1, files’ names HeaderL2Lab1.h, ImpL2Lab1.cpp, MainL2Lab1.cpp]

    ✍ How to do:

    1. Open Microsoft Visual Studio. Select menu item File -> New project. In the Template region find C++ and then, Win32 Console Application.
    2. Create a new console project, name your project Lesson_2Lab1. Among the Additional options mark Empty project and nothing more must be marked. Click Finish button.
    3. In the Solution Explorer window find a Source files folder, click the right mouse button on it and select Add -> New Item. We’re going to create two .cpp files. Call them ImpL2Lab1.cpp – implementation file and MainL2Lab1.cpp – file with a main function.
    4. Now, find a Header files folder, click the right mouse button on it and select Add -> New Item. We’re going to create .h file, and give it a name HeaderL2Lab1.h.
    5.   
      1) Without using functions and multi-file application:

    6. First, we’re going to make this task without functions and encapsulation. So, we should set the cube side length value, and calculate the cube volume and surface area.
    7. Declare a variable of type double for length and set a value for it. Don’t forget to include iostream header, since we’re going to read/write to the console:
    8. #include <iostream>
      int main() {
      double length;
      	std::cout << "please enter the cube side length: ";
      	std::cin >> length;
      	// …
      }
      
    9. To prevent console window from closing, you should use pause. The main function must return 0:
    10. //…
         system("pause");
         return 0;
      }
      
    11. Declare variables for the cube volume and surface area. Calculate the values for them:
    12. 	double volume = length * length * length;
      	double surfaceArea = 6 * length * length;
      
    13. After, you can print out the result to the console:
    14.    std::cout << "Volume: " << volume << std::endl;
         std::cout << "Surface area: " << surfaceArea << std::endl;
      
    15. Run the application and check the output.
    16.  
      2) Using functions:

    17. We’re going to modify our application creating methods to calculate the values of volume and surface area.
    18. Find the lines with the variables declarations and calculations and comment them out:
    19. //double volume = length * length * length;
      //double surfaceArea = 6 * length * length;
      
    20. Let’s create a method named getVolume to calculate a cube volume. It must return double type, since the cube side length is also of double type. Before the method signature you should define the method. You must add the code before the main function:
    21. double getVolume(double length);
      double getVolume(double length)
      {
      	return length * length * length;
      }
      int main() {
          //…
      
    22. Place the declaration of the length inside the main function:
    23. int main() {
      	double length;
      
    24. Create a method named getSurfaceArea to calculate a cube surface area. It must be of double type too. Place the code before the main function:
    25. double getSurfaceArea(double length);
      double getSurfaceArea(double length) {
      	return 6 * length * length;
      }
      
    26. The compiler doesn’t run functions until we call them. Therefore, you must call your methods. Now you can use the variables to store the function returning results. Place the code inside the main function:
    27. double volume = getVolume(length);
      double surfaceArea = getSurfaceArea(length);
      
    28. Run the application and check the output. The results must be as they were.
    29. 3) Creating a multi-file application

    30. We’re going to modify our application creating a multi-file one.
    31. In the Solution Explorer window select (mouse double click) the header file you created (HeaderL2Lab1.h). Inside the code editor window, you must add your method declarations only (you can cut them from your main file and paste here):
    32. #pragma once
      // calculates a cube volume
      double getVolume(double length);
      // calculates a cube surface area
      double getSurfaceArea(double length);
      
      — Notice in this .h file we have not defined how getVolume works, how getSurfaceArea works. All we’ve done is declare that these are the functionalities of our program. We need to look at our .cpp file to find out how they actually work.
      — This pragma once line instructs the compiler to only compile this code once. Even if multiple people use our class, we’ll only want the definition of our methods to be defined exactly once.
      — Note that you should always place the comments before each function.
    33. In the Solution Explorer window select (mouse double click) the implementation file you created (ImpL2Lab1.cpp). Inside the code editor window, you must add your method functionalities (cut them from the main file and paste here). And don’t forget to include the header file first:
    34. #include "HeaderL2Lab1.h"
      double getVolume(double length)
      {
      	return length * length * length;
      }
      double getSurfaceArea(double length) {
      	return 6 * length * length;
      }
      
      — We call this file the implementation file and it’s the code that contains all of the logic to implement our methods.
      — We have a pound (#) include that includes a reference to our header.
      — We have the implementation of our two functions that were defined in our .h file.
    35. Now, we can go ahead and clear up the parts of a code we don’t need anymore within the main function. So, this is what you have in your MainL2Lab1.cpp:
    36. #include <iostream>
      #include " HeaderL2Lab1.h"
      int main(){
      	double length;
      	std::cout << "please enter the cube side length: ";
      	std::cin >> length;
              //double volume = length * length * length;
      	//double surfaceArea = 6 * length * length;
      	double volume = getVolume(length);
      	double surfaceArea = getSurfaceArea(length);
      	std::cout << "Volume: " << volume << std::endl;
      	std::cout << "Surface area: " << surfaceArea << std::endl;
      	system("pause");
      	return 0;
      }
      
    37. Run the application and check the output. The results must be as they were.
    38. Three files must be uploaded to the moodle system: HeaderL2Lab1.h, ImpL2Lab1.cpp, MainL2Lab1.cpp.

    Notes on all tasks

  • To make the following tasks you’ll need 3 files: tasks.h, tasks.cpp, main.cpp. Download them and place them into the Lesson_2Lab1 folder.
  • When all the tasks you intended to do have been completed, upload those three files to the moodle.
  • [Solution and Project name: Lesson_2Lab1, files’ names tasks.h, tasks.cpp, main.cpp]

    Task 0:

    To do: Create a Sum() method that takes two integer arguments and sums them. The method returns the result of integer type.

    Note: You need to create the method declaration in the tasks.h file by yourself, and also the method implementation must be written in the tasks.cpp file. Call the function within the main.cpp. Don’t forget to use the comments to explain the purpose of the method.

    Expected output:

    Please, enter two numbers
    20 40 
    The sum of 20 and 40 is: 60
    

    [Solution and Project name: Lesson_2Lab1, files’ names tasks.h, tasks.cpp, main.cpp]

    Task 1:

    To do: Ask user to enter the lengths of the three sides of the triangle. Create a function named perimeter that calculates the perimeter of a triangle from the lengths of its three sides (with integer arguments). Create an overloaded function with the same name for real arguments.

    Note: Three files may be used to complete the task. Check the code of the files and fill in the places marked as // TODO related to this task. (this note is not obligatory)

    Expected output:

    please enter three numbers for the triangle three sides: 3.0  4.1  5.0
    the perimeter is: 12.1
    

    [Solution and Project name: Lesson_2Lab1, files’ names tasks.h, tasks.cpp, main.cpp]

    Task 2:

    To do: Ask user to enter the lengths of the three sides of the triangle. Create a function named areaFromSides that calculates the area of a triangle by the lengths of its three sides using Heron’s formula:

    where p stands for semi-perimeter.

    Note 1: Three files may be used to complete the task. Check the code of the files and fill in the places marked as // TODO related to this task.

    Note 2: To calculate a square root the math libtary is needed to be included and sqrt() function:

    #include <cmath>

    Expected output:

    please enter three numbers for the triangle three sides: 
    2 4 5
    the area is: 6
    

    [Solution and Project name: Lesson_2Lab1, files’ names tasks.h, tasks.cpp, main.cpp]

    Task 3:

    To do: Ask user to enter the coordinates of triangle vertices ((x1,y1); (x2,y2); (x3,y3)). Create a method named areaFromPos that calculates the area of a triangle using the coordinates of its vertices. Add a default parameter value for one of the vertices (0,0).

    Note 1: Three files must be used to complete the task. Check the code of the files and fill in the places marked as // TODO related to this task.

    Note 2: The math libtary is needed:

    #include <cmath>

    Expected output:

    please enter six numbers for the coordinates of the triangle vertices:
    4 6 2 9 1 7
    the area is: 3
    

    [Solution and Project name: Lesson_2Lab1, files’ names tasks.h, tasks.cpp, main.cpp]

    Task 4:

    To do: Ask user to enter the coordinates of two points. Create a function named dist that calculates the distance between two points on the plane, using their coordinates. [sqrt]. Add function overload for real coordinate values.

    Note: Formula to calculate the distance between two points:

    Note: To check to see if your result is right you can calculate the distance in the wolframalpha service. For example, to find the distance between points (1, -2) and (4, 2), use command distance ({1, -2}, {4, 2}).

    Note: Three files must be used to complete the task. Check the code of the files and fill in the places marked as // TODO related to this task.

    Expected output:

    Please enter the coordinates of two points (four integers: x1, y1, x2, y2):
    1 -2  4  2
    The distance is: 5
    

    [Solution and Project name: Lesson_2Lab1, files’ names tasks.h, tasks.cpp, main.cpp]

    Task 5:

    To do: Create GetPow() function that takes two integer arguments, they are base number and power number. The function returns the result of taking a base number to power number.

    Note: Three files must be used to complete the task. Check the code of the files and fill in the places marked as // TODO related to this task.

    Expected output:

    Please enter two numbers – a base number and a power number:
    2  4 
    Base number 2 raised to the power number 4 = 16
    

    [Solution and Project name: Lesson_2Lab1, files’ names tasks.h, tasks.cpp, main.cpp]

    Task 6:

    To do: Define Mean(X, Y) function that calculates the arithmetic mean and geometric mean ((√X*Y)) of two positive decimal numbers X and Y. X and Y are input parameters. The function must not return any values, it has to print the results out to the console window.

    Note: You can use the standard function to calculate the square root of a number (sqrt()). But you need to include a math library:

    #include <cmath>

    Note: To print out the floating point number with 3 digits after the point, you should use the following function:

    printf("%.3f ",result)

    Expected output:

    please enter two numbers: 
    
    <<15.0  <<4.0
    arithmetic mean: 9.500
    geometric mean: 7.746
    

    [Solution and Project name: Lesson_2Task6, files’ names task6.h, task6.cpp, main6.cpp]

    Tasks for self-solving:

    Note: tasks should be saved in a file with the name of the task, and be sure to insert a comment with the statement of the task in the code.

    Proc

    1. Proc16. Write an integer function Sign(X) that returns the following value:
    2. −1,    if X < 0;        0,    if X = 0;        1,    if X > 0

      (X is a real-valued parameter). Using this function, evaluate an expression Sign(A) + Sign(B) for given real numbers A and B.

      Expected output:
      << A = -6.20  B = 0.00
      results:
      sign(A) + sign(B) = -1
      
    3. Proc18. Write a real-valued function CircleS(R) that returns the area of a circle of radius R (R is a real number). Using this function, find the areas of three circles of given radiuses. Note that the area of a circle of radius R can be found by formula S = π·R2. Use 3.14 for a value of π.
    4. Expected output:
      << R1=8.06 R2=0.84 R3=4.30 
      results:
      CircleS(R1)=203.99
      CircleS(R2)=2.22
      CircleS(R3)=58.06
      
    5. Proc28. Write a logical function IsPrime(N) that returns True, if an integer parameter N (> 1) is a prime number, and False otherwise. Using this function, find the amount of prime numbers in a given sequence of 10 integers greater than 1. Note that an integer (> 1) is called a prime number if it has not positive divisors except 1 and itself.
    6. Expected output:
      << 14 89 83 84 38 97 398 15 282 679
      results:
      3
      
    7. Proc34. Write a real-valued function Fact(N) that returns a factorial of a positive integer N: N! = 1·2·…·N (the real return type allows to avoid the integer overflow during the calculation of the factorials for large values of the parameter N). Using this function, find the factorials of five given integers.
    8. Expected output:
      << N1=5 N2=9 N3=3 N4=27 N5=15
      results:
      Fact(N1)=1.200000E+002
      Fact(N2)=3.628800E+005
      Fact(N3)=6.000000E+000
      Fact(N4)=1.088887E+028
      Fact(N5)=1.307674E+012
      
    * The tasks are taken from M. E. Abramyan (Southern Federal University) Programming Taskbook