20. Exercises – Modern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards

© Slobodan Dmitrović 2020
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_20

20. Exercises

Slobodan Dmitrović1 
(1)
Belgrade, Serbia
 

20.1 Function Definition

Write a program that defines a function of type void called printmessage() . The function outputs a "Hello World from a function." message on the standard output. Call the function from main.
#include <iostream>
void printmessage()
{
    std::cout << "Hello World from a function.";
}
int main()
{
    printmessage();
}

20.2 Separate Declaration and Definition

Write a program that declares and defines a function of type void called printmessage(). The function outputs a "Hello World from a function." message on the standard output. Call the function from main.
#include <iostream>
void printmessage(); // function declaration
int main()
{
    printmessage();
}
// function definition
void printmessage()
{
    std::cout << "Hello World from a function.";
}

20.3 Function Parameters

Write a program which has a function of type int called multiplication accepting two int parameters by value. The function multiplies those two parameters and returns a result to itself. Invoke the function in main and assign a result of the function to a local int variable. Print the result in the console.
#include <iostream>
int multiplication(int x, int y)
{
    return x * y;
}
int main()
{
    int myresult = multiplication(10, 20);
    std::cout << "The result is: " << myresult;
}

20.4 Passing Arguments

Write a program which has a function of type void called custommessage. The function accepts one parameter by reference to const of type std::string and outputs a custom message on the standard output using that parameter’s value. Invoke the function in main with a local string.
#include <iostream>
#include <string>
void custommessage(const std::string& message)
{
    std::cout << "The string argument you used is: " << message;
}
int main()
{
    std::string mymessage = "My Custom Message.";
    custommessage(mymessage);
}

20.5 Function Overloads

Write a program that has two function overloads. The functions are called division, and both accept two parameters. They divide the parameters and return the result to themselves. The first function overload is of type int and has two parameters of types int. The second overload is of type double and accepts two parameters of type double. Invoke the appropriate overload in main, first by supplying integer arguments and then the double arguments. Observe different results.
#include <iostream>
#include <string>
int division(int x, int y)
{
    return x / y;
}
double division(double x, double y)
{
    return x / y;
}
int main()
{
    std::cout << "Integer division: " << division(9, 2) << '\n';
    std::cout << "Floating point division: " << division(9.0, 2.0);
}