Solutions

9. Functions

#include <iostream>
using namespace std;

double Sub(double a, double b)
{
    return a-b;    
}

int main()
{
    cout << "3.2 - 8 = " << Sub(3.2, 8) << endl;    
}

Exercise 2:

#include <iostream>
using namespace std;

double Add(double a, double b) { return a+b; }
double Sub(double a, double b) { return a-b; }
double Mul(double a, double b) { return a*b; }

int main()
{
    cout << "a) " << Add(Add(1,3),5) << endl; // or: Add(1,Add(3,5))
    cout << "b) " << Add(Add(Add(Add(1,3),5),7),4) << endl;
    // or: Add(1,Add(3,Add(5,Add(7,4)))), or in some other order
    cout << "c) " << Sub(10,Add(3,5)) << endl;
    cout << "d) " << Sub(10,Mul(3,5)) << endl;
    cout << "e) " << Mul(Sub(10,3),5) << endl;
    cout << "f) " << Sub(Sub(11,5),2) << endl;
    cout << "g) " << Add( Sub(Mul(2,16),Mul(4,7)), Mul(2,Sub(Sub(4,3),2)) )
         << endl;
 }

Back to exercises