solutions

up

back

 

chapter 1 chapter 2 chapter 3

Home keywords c bibliography

 

solutions chapter 2

    Exercise 2        Calculation of eulers number

The following program calculates eulers number iteratively. Note that we change the output precision to 10 digits. Also we compare the calculated value with a value returned by a call to the exponential function of the math library. For the use of the double-type see chapter 3. What happens if we change the "e+=1.0/nf" in "e+=1/nf"?

#include <iostream>
#include <math.h>

int main()
{
    int i,nf=1;
    double e=0.;
    cout.precision(10);
    for (i=0;i<=10;i++)
    {
        e+=1.0/nf;
        nf*=i+1;
        cout << i << "\t" << e << "\t" << exp(1) << endl;
    }
}

 

    Exercise 3        Calculation of the prime numbers between 3 and 100

One possible solution is given by the following program. The outer for-loop loops over the numbers from 3 to 100. The inner while-loop increases the variable j, until either i is dividable by j without rest, or j reaches i-1. If after this loop j has the value of i-1 it means, that we did not found a number by which i may be divided without rest and so for i is a prime number.

#include <iostream>

int main()
{
    int i,j;
    for (i=3;i<=100;i++)
    {
        j=2;
        while (((i%j) != 0) && j<(i-1)) j++;
        if (j==i-1) cout << i << endl;
    }
}

Of course one can construct different loops with different control structures. Like in this example there is often more than one way of realizing simple algorithms.

email me: Daniel Schürmann