Next: Example while loop: Average,
Up: The while statement
Previous: Example while loop: Summing
The following program produces a table of x and sin(x)
as x takes values 0 to 90 degrees in steps of 5 degrees. Note
that the C++ sin function takes an argument in radians, not in
degrees. In the program below sin(radian) returns the sine of
an angle radian expressed in radians. The mathematical function
library will be covered in more detail in section 20.2.
// IEA Oct. 95
// Tabulates x and sin(x)
#include <iostream.h>
#include <math.h> // because we are going to use
// a mathematical function
void main()
{
const float degtorad = M_PI/180; // convert degrees
// to radians
int degree = 0; // initialise degrees to zero
float radian; // radian equivalent of degree
// Output headings
cout << endl << "Degrees" << " sin(degrees)"
<< endl;
// Now loop
while (degree <= 90)
{
radian = degree * degtorad; // convert degrees to
// radians
cout << endl << " " << degree << " "
<< sin(radian);
degree = degree + 5; // increment degrees
}
cout << endl;
}
Download program.
Note that the mathematical constant
is defined in the
mathematical library as M_PI.