C++

Functions in C++ with Examples – 1

EXERCISE 1

Write a distance function whose parameters are 4 doubles xa, ya and xb, yb which represent the coordinates of two points A and B and which returns the distance AB. Test this function.




The purpose of this exercise is to check the following technical points:

Simple function creation.
Parameter passing by value.
Using return.
Call a function.

Here is the source file:

 

EXERCISE 2

Write a function f having as parameters a double x and a boolean ok and which returns a double by a return. The function returns with a return the square root of (x-1) * (2-x). The function returns the value true if the function is defined at x, otherwise false. Test this function.

The purpose of this exercise is to check the following technical points:

Simple function creation.
Passing parameters by value and by reference.
Using return.
Input and output parameters of a function.
Call a function.
Game of tests of a function.
Here is the source file:

 

EXERCISE 3

Write a function f having an integer parameter and returning a Boolean return: true if the integer is first false otherwise. Test this function.

The purpose of this exercise is to check the following technical points:

Simple function creation.
Call a function.
Validation of data before calling a function.
Function returning a boolean.
Here is the source file:

 

EXERCISE 4

Write a function f having as parameter an integer n and which returns the nth prime number: this function will use the function of 3). Test this function.

The purpose of this exercise is to check the following technical points:

Creation of simple functions.
Function call.
Function that calls another function.
Here is the source file:

 

EXERCISE 5

Write a swap function with parameters 2 integers a and b that exchange the contents of a and b. Test this function.

The purpose of this exercise is to check the following technical points:

Simple function creation.
Call a function.
Parameter passing by references.
Here is the source file:

 

 

About the author

admin

Leave a Comment