CS 205 - Programming for the Sciences
Spring 2008 - Exam 2 Answers


Problem 1

Highest, lowest, range of elements in an array


private void range_Click(object sender, EventArgs e)
{
    int smallest = values[0],  // Initialize to first value in array
        largest = values[0];
    for (int i = 1; i < NUM_VALUES; i++)  // For each value in array
    {
        if (values[i] < smallest)         // Look for a smaller value
            smallest = values[i];
        if (values[i] > largest)          // Look for a larger value
            largest = values[i];
    }

    // Display results
    results.Items.Add("The smallest value is " + smallest);
    results.Items.Add("The largest value is " + largest);
    results.Items.Add("The range is " + (largest - smallest));
}


Problem 2

Matrix Transpose


private void transpose_Click(object sender, EventArgs e)
{
    double[,] matrixA = ReadMatrix(matA);

    // declare and create a result matrix
    double[,] matrixAtr = new double[MATRIX_SIZE, MATRIX_SIZE];
    for (int i = 0; i < MATRIX_SIZE; i++)
        for (int j = 0; j < MATRIX_SIZE; j++)
            matrixAtr[i, j] = matrixA[j, i];

    // "copy" result matrix into the matResult grid of textboxes
    for (int row = 0; row < MATRIX_SIZE; row++)
        for (int col = 0; col < MATRIX_SIZE; col++)
            matAtr[row, col].Text = matrixAtr[row, col].ToString();
}



Problem 3

Complex Numbers

In Complex.cs


public double AbsoluteValue()
{
    return Math.Sqrt(real * real + imaginary * imaginary);
}

public static Complex operator +(Complex left, Complex right)
{
    return new Complex(left.real + right.real,
        left.imaginary + right.imaginary);
}

public static Complex operator *(Complex left, Complex right)
{
    return new Complex(left.real * right.real - 
        left.imaginary * right.imaginary,
        left.imaginary * right.real + left.real * right.imaginary);
}


In Form1.cs


private void calculate_Click(object sender, EventArgs e)
{
    // Get complex numbers from textboxes
    Complex c1 = Complex.Parse(leftComplex.Text),
        c2 = Complex.Parse(rightComplex.Text),
        result;
    string answer = 
        c1.ToString() + ' ' + anOp.Text + ' ' + c2 + " = ";

    switch (anOp.Text)  // See which operation it is
    {
        case "+":
            result = c1 + c2;
            break;
        case "*":
            result = c1 * c2;
            break;
        default:
            throw new Exception("Complex Demo: unknown operator");
    }

    // Display result
    results.Items.Add(answer + result);
}

private void absolute_Click(object sender, EventArgs e)
{
    // Get complex number from textbox
    Complex c = Complex.Parse(aComplex.Text);

    // Display result
    results.Items.Add("The absolute value of " + c + " is " 
        + c.AbsoluteValue());
}

04/28/08 1 of 3