CS 205 - Programming for the Sciences
Spring 2008 - Practice Exam 1, Part 2 Answers

Problem 1

Area of a regular polygon


private void area_Click(object sender, EventArgs e)
{
    // Get user input
    int n = Convert.ToInt32(numSides.Text);
    double r = Convert.ToDouble(radius.Text);

    // Compute angle and area
    double alpha = (2 * Math.PI) / n;
    double area = .5 * n * r * r * Math.Sin(alpha);

    // Display results
    results.Items.Add("The area is " + area.ToString()
                       + " square inches");
}


Problem 2

Convert 24-hour time to 12-hour time


private void regTime_Click(object sender, EventArgs e)
{
    // Get user input
    int time24 = Convert.ToInt32(time.Text);
    
    // Compute hours and minutes of 24-hour time
    int hours = time24 / 100, 
        minutes = time24 % 100;

    // Determine AM/PM indicator
    string indicator;
    if (hours < 12)
        indicator = "AM";
    else
        indicator = "PM";

    // Adjust hours to 12-hour notation
    if (hours == 0)
        hours = 12;
    else if (hours > 12)
        hours = hours - 12;

    // Display results
    results.Items.Add("Time in 12-hour notation is " + hours.ToString()
                      + ':' + minutes.ToString("00") + indicator);
}



Problem 3

Approximation of π


private void calc_pi_Click(object sender, EventArgs e)
{
    // Get user input
    int nt = Convert.ToInt32(numTerms.Text);

    double sum = 0, pi;

    // Compute sum of terms, counting 0 to n < nt give nt terms
    for (int n = 0; n < nt; n++)
    {
        if (n % 2 == 0)  // n is even, so positive term
            sum = sum + 1.0 / (2 * n + 1);
        else // n is odd, so negative term
            sum = sum - 1.0 / (2 * n + 1);
    }
    pi = 4 * sum;

    // Display result and built-in value of pi
    results.Items.Add("Approximation of pi is " + pi.ToString());
    results.Items.Add("Math.PI is " + Math.PI.ToString());
}

02/14/08 2 of 2