Tuesday, March 25, 2014

Final Review_27_28 (Message Box with Array)

Ex 27.    Use a loop to add all the negative values in the array above. Display the sum in a message box.
Ex 28.    Use a loop to determine the average value of only the positive values in the array. Display the average value.


//=================Ex 27==============================
        private void btnNegSum_Click(object sender, EventArgs e)
        {

            double[] A = { -3.5, 2.3, 5.9, -6.9, -12.1, 15.6, 4.7, -3.8, -17.3, -11.4, 12.6, 19.9 };
            double NegSum = 0;
            for (int i = 0; i < A.Length; i++)
            {
                if (A[i] < 0)
                {
                    NegSum += A[i];
                }
            }
            MessageBox.Show(NegSum.ToString());
        }
        //=================Ex 28==============================
        private void btnAvgOfP_Click(object sender, EventArgs e)
        {
            double[] A = { -3.5, 2.3, 5.9, -6.9, -12.1, 15.6, 4.7, -3.8, -17.3, -11.4, 12.6, 19.9 };
            double SumP = 0;
            double denominator = 0;
            for (int i = 0; i < A.Length; i++)
            {
                if (A[i] > 0)
                {
                    SumP += A[i];
                    denominator++;
                }
            }
            double AvgOfP = SumP / denominator;
            MessageBox.Show(AvgOfP.ToString("f3"));
        }
    }
}

No comments:

Post a Comment