Next: Streams and External Files Up: The for statement Previous: Review Questions

Exercises

  1. Write an algorithm for a program to produce the sum of the series

    \begin{displaymath}
1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots + \frac{1}{n}
\end{displaymath}

    where n is entered by the user. Then write and test the program.

    Change your algorithm so that the sum of the series

    \begin{displaymath}
1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \cdots \frac{1}{n}
\end{displaymath}

    is computed. Then write and test the program. As n gets larger the results should tend towards 0.7854 ($\pi$/4).

  2. In exercise 1 of Lesson 16 you wrote a program to enter a set of numbers and to output counts of the number of negative and positive numbers. Change that program so that it asks the user how many numbers are to be entered and uses a for loop.

  3. In exercise 3 of Lesson 16 it was described how random integers could be generated by the rand function. This routine can also be used to generate random fractions in the range 0-1. Since rand() generates an integer between 0 and RAND_MAX-1 then rand()/float(RAND_MAX) generates a fraction in the range (0,1). If $x$ is a random number in the range (0,1) then $1-2x$ is a random fraction in the range (-1,+1). Start by writing a program that produces n (entered by user) pairs of random fractions in the range (-1,+1). Use a for loop to implement the loop.

    Once this is working extend your program as follows. Treat each pair of random values as the co-ordinates of a point $(x,y)$ and output a count of how many of the generated points lie inside a circle of radius 1 and centre at (0,0) i.e. $x ^ 2 + y ^ 2 < 1$.

    If the random number generator used is reasonably uniform in its distribution of numbers then the probability that a point lands in the circle is the ratio of the area of the circle to the area of the $2\times2$ square centred on the origin. This ratio is $\pi/4$. Thus an estimate of the value of $\pi$ can be made from the ratio of the count of points inside the circle to the total number of points. Hence extend your program to output an estimate of $\pi$. This is known as a Monte Carlo method. Run your program a few times with increasing values of n to see how the estimate of $\pi$ improves with the number of trials carried out.

  4. Write an algorithm to produce an n times multiplication table ( n less than or equal to 10). For example, if n is equal to four the table should appear as follows:
       1    2    3    4
    1  1    2    3    4
    2  2    4    6    8
    3  3    6    9   12
    4  4    8   12   16
    
    Convert your algorithm into a program. Use nested for loops and pay attention to formatting your output so that it is displayed neatly.



Next: Streams and External Files Up: The for statement Previous: Review Questions