AllTheTimeWorld.com

csharp arithmeticWrite a function

Write a function

Write a function to avoid the same code in two places

Write a function

Write a function to avoid the same code in two places

The grade program has exactly the same code in two places. This is a very bad idea. If we need to change it, we have to change it in two places.

Modify the grade program by writing a function calculateGrade. You will need to write the function header yourself, then call the function from each of the scroll events:

Write the code as shown below:

// Programmer: Janet Joy
// Calculate average from midterm and final grade.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace grades
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void hsbMidterm_Scroll(object sender, ScrollEventArgs e)
        {
            // Call the function to calculate grade when the midterm changes.
            calculateGrade(); 
        }

        private void hsbFinal_Scroll(object sender, ScrollEventArgs e)
        {
            // Call the function to calculate grade when the final changes.
            calculateGrade(); 
        }
        
        private void calculateGrade()
        {
            // Calculate grade when either midterm or final changes
            int midterm = hsbMidterm.Value;
            int final = hsbFinal.Value;
            double average = (midterm + final) / 2;
            lblMidterm.Text = "Midterm: " + midterm;
            lblFinal.Text = "Final: " + final;
            lblAverage.Text = "Average: " + average;
        }
    }
}


Remember, you should try doing each of these programs on your own. Get it to work, break it, modify it, and then try to write it on your own!