Simple Calculator in C#

Posted by admin on August 14, 2010

Lets see how easy C# really is by developing a simple calculator.

First open visual C# studio and go to File>New Project> A new project window will open, click on ” Windows Forms Applications” Then name your file  Calculatorcs  then chose a location to save your project then press the OK button. Your “Solution Explorer” window should open. Then you want to double click Form1.cs in the Solution Explorer to bring up the design form.

bring up Form1.cs design page.

Form1.cs

Now that you have the design page open here comes the easy part. Click on the hammer and wrench icon in the menu ribbon to bring up your tools pane.

Finding your tools window.

Your going to drag and drop all the items your calculator is going to use for you to interact with it. Your going to drag and drop five buttons and one TextBox onto your form and arrange them as such as shown in the image below.  It’s easier if you do one button at a time setting the size in the properties to (33, 33) for the first four buttons and (75, 23) for the clear button, so that getting them to fit on the form doesn’t become a problem. Then set the property values for each button and the TextBox as instructed below.

  

Now one at a time hover your mouse over each button right clicking and choosing properties. There you will chose a name for each button( add, sub, mul, div , eq, clear) then the size for each button if you haven’t done it already(33, 33) for the first four buttons then (75, 23 ) for the clear button,  then the text for each button ( +, -, x, /, =, Clear).

Now for the TextBox, hover over it with your mouse, right click and chose properties and for the name call it tb. You don’t need to set the text for the TextBox.

Now your interface is ready to be connected to the code that’s going to run your program. Your Form should look like this after setting the size and text for each button.

This is what your form should look like.

Now lets create the code that going to make this a calculator in C#.

This is where we learn that C# is not just a language but it’s a programing environment when using Microsoft’s Visual C# Compiler. The compiler has written all the code to create what you have already, the body of the calculator, the buttons, and TextBox. It will now write the code to connect the visual part of the calculator to the code that will give functionality to the calculator.

We will start this off by double clicking each one of the buttons.  This will create code segments called methods or in other languages like c++ functions for us to write our code in.

After double clicking all of the buttons hover over the Frame1 and right click then click “view Code” This will open the code page for coding your buttons.  You should find code that looks like the code I have below.

     private void eq_Click(object sender, EventArgs e)
        {
            //code for the equal button

        }

        private void add_Click(object sender, EventArgs e)
        {

        //code for the add button   

        }

        private void sub_Click(object sender, EventArgs e)
        {
          //code for the sub button
        }

        private void mul_Click(object sender, EventArgs e)
        {
          //code for the mul button
        }

        private void div_Click(object sender, EventArgs e)
        {
         //code for the div button
        }

        private void clear_Click(object sender, EventArgs e)
        {
         //code for the clear button
        }
    }

Visual C# has written this code and a lot more for you. You just need to write the code inside of each of these methods to make something happen when a particular button is clicked. But most of the code your going to write is also methods and classes that refer to reusable code from libraries.

Lets look at a few of these methods and classes that will be used in our calculator that may use hundreds of line of reusable code.

float.TryParse(‘name of TextBox’.Text, out ‘variable’);

float.TryParse(tb.Text, out a);

float.TryParse(tb.Text, out b);

The code above takes the literal numbers in the TextBox named tb and converts them to their numerical value and stores this value in a variable called a and b. These variables a and b will store our input numbers from our calculator.

The next line of code we will look at will convert our numerical answer in to a literal char and send it to our TextBox tb.

tb.Text = (c.ToString());

We put our answer into a variable float c, the code above converts the float c to a char string and sends it to our TextBox tb.

We will also use a couple other methods in our calculator;

tb.Clear();     // This clears the TextBox tb.

tb.Focus();  // This set the focus to the TextBox tb.

Write these functions, methods and classes down and how they work. The same way a lead guitarist  learns melodic riffs and puts them together to create a song a programmer puts together all these little bits of code called functions, methods, and classes to develop a program. This is also why the C# .Net Framework by Microsoft is better then the other languages, Microsoft has worked hard at creating lots of these robust, easy to use, very useful reusable code bits. The only problem is Microsoft’s help that describes these functions, methods and classes is just about useless. The noob (Never feel bad about being called a noob, it just means your on the road to success.) is left out in the cold.

Now lets do some coding. We need to initialize some variables for our calculator. Right click the form and click view code. Look for the form class and incert the following code.

 // Initialize some variables
float a, b, c, z;
float f = 0;
char math_pros;

This gives us some places to store values we’ll be working with.

This is how it will work:

A number is added to the TextBox, but this number is view as a character string, not a number. Nothing will happen until an operation is clicked like the add button.

Once the add button is clicked the method visual C# has written for you will be called that will contain the code you have written to be performed as shown below.

    private void add_Click(object sender, EventArgs e)
        {
           /* Here the math_pros variable is set to char 'a'
             to let the equals operation know that the add button has
             been clicked */

            math_pros = 'a'; 

           // This code allows you to add more then two numbers.
            float.TryParse(tb.Text, out z);
            a = z + f;
            f = a;
         // This clears the TextBox and set the focus
            tb.Clear();
            tb.Focus();
        }

This  method float.TryParse(tb.Text, out z);  from the code above will change the character string into a numerical value and store it in the z variable.

Then the next number will be entered onto the TextBox and the equals button will be clicked. This will cause the code to be executed that you have places in the equals method that Visual C# has written for you and so on and so on.

As you can see, Visual C# and Microsoft has done most of the coding. To do this simple programming task with out Visual C#’s compiler and the libraries from Microsoft would have taken years of experience, knowledge and a lot of time coding.

Although Microsoft is trying to appear as a good fellow they change their compilers and the way things are done every few years making much of the examples on the Internet useless to noob and the struggling. As an example, the help for the 2010 Visual C# environment is nonexistent.

So you might want to get the 2008 Visual studio express while you still can to get the offline help it offered.

Below is the rest of the coding for the calculator.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace calculatorcs
{
    public partial class Form1 : Form
    {
        // Initialize some variables
        float a, b, c, z;
        float f = 0;
        char math_pros;

        public Form1()
        {
            InitializeComponent();
        }

        // Below is the code used when the equals button is pressed.
        private void eq_Click(object sender, EventArgs e)
        {
            // This checks what operation is going to be performed.
            float.TryParse(tb.Text, out b);
		if ( math_pros == 'm' ){
		c = a * b;
		}
		if ( math_pros == 'd' ){
		c = a / b;
		}
		if ( math_pros == 's' ){
		c = a - b;
		}
		if ( math_pros == 'a' ){
		c = a + b;
		}

		tb.Text = (c.ToString());

        /* After clicking on the equals button and performing
         the required tasks everything is set to zero again.*/
        f = 0;
        c = 0;
        b = 0;
        z = 0;
        }

        // Below is the code used when the add button is clicked.
        private void add_Click(object sender, EventArgs e)
        {
           /* Here the math_pros variable is set to char 'a'
             to let the equals operation know that the add button has
             been clicked */

            math_pros = 'a'; 

           // This code allows you to add more then two numbers.
            float.TryParse(tb.Text, out z);
            a = z + f;
            f = a;
         // This clears the TextBox and set the focus
            tb.Clear();
            tb.Focus();
        }

        private void sub_Click(object sender, EventArgs e)
        {
            math_pros = 's';

            float.TryParse(tb.Text, out a);

            tb.Clear();
            tb.Focus();
        }

        private void mul_Click(object sender, EventArgs e)
        {
            math_pros = 'm';

            float.TryParse(tb.Text, out a);

            tb.Clear();
            tb.Focus();
        }

        private void div_Click(object sender, EventArgs e)
        {
            math_pros = 'd';

            float.TryParse(tb.Text, out a);

            tb.Clear();
            tb.Focus();
        }
        // This code below sets everything back to zero and clears the TextBox
        private void clear_Click(object sender, EventArgs e)
        {
            c = 0;
            b = 0;
            a = 0;
            tb.Clear();
            tb.Focus();
        }
    }
}

If you have any problems with this program please leave a comment below and I’ll address them as soon as I get time.

Filed under Learning C#

«

Comments are closed.