- Addition
- Subtraction
- Division
- Multiplication
- Square Root
- Exponents (Power Of)
- Clear Entry
- Clear All

- Adding a number to memory
- Removing a number from memory
- Calculating with a number in memory
- Entering numbers by typing

Your user interface will consist of

- Buttons 0 through 9
- Buttons for

- Addition

- Subtraction

- Division

- Multiplication

- Exponents (x^)

- Inverse (1/x)

- Square Root (sqrt)

- Addition
- Decimal
- Equals
- Backspace
- CE (Clear Entry)
- C (Clear All)
- ReadOnly TextBox for input (Make sure TabStop is also set to False)

- System.Math.Sqrt Method Used to calculate Square Roots
- System.Math.Pow Method Used to calculate Exponents

Now, in our calculator we need some

**Global**variables to hold different items and states in our calculator, such as which calculation are we performing, does the input area already have a decimal, whether we can enter values into the input area and to hold values while we perform calculations. Add the following code to the top of your code, this is the global variables we need in our calculator:

//variables to hold operands private double valHolder1; private double valHolder2; //Varible to hold temporary values private double tmpValue; //True if "." is use else false private bool hasDecimal = false; private bool inputStatus = true; //variable to hold Operater private string calcFunc;

These variables will be used through out our program thats why they're globals. Now, before any calculations can be done, the user needs to be able to enter numbers into the input box, so lets take a look at how to do that. Since all the number keys in the calculator are the same (except the 0 (zero) key, we'll conver that in a minute) I will code one of the buttons, then you can do the rest. Lets take a look at the number one key:

private void cmd1_Click(object sender, System.EventArgs e) { //Check the inputStatus if (inputStatus) { //Its True //Append values to the value //in the input box txtInput.Text += cmd1.Text; } else { //Value is False //Set the value to the value of the button txtInput.Text = cmd1.Text; //Toggle inputStatus to True inputStatus = true; } }

When a user clicks a number button (in this case the number one button) we check the status of the inputStatus flag. If its true then we know we can just append the next value to the end of whats currently in the input box, otherwise we just enter the number into the input box. All the remaining numbers, as stated before, follow this procedure. The zero button slightly different as we don't want the user to be able to enter zero as the first number (this is covered more in the decimal button functionality). So lets take a look at how we code the zero button:

private void cmd0_Click(object sender, System.EventArgs e) { //Check the input status if (inputStatus) { //If true //Now check to make sure our //input box has a value if (txtInput.Text.Length >= 1) { //Add our zero txtInput.Text += cmd0.Text; } } }

First we check the status of the

**inputStatus**flag, if its true we know we can enter a number in the box. Here we do a second check, we make sure the length of the text in the input box is at least 1 (it has a value), if so we enter the zero into the input box.

For adding a decimal to our input box we need to first make sure our input box doesn't already contain one, for this we use the

**hasDecimal**global (boolean) variable, then we need to make sure our input box has a value (don't want the user to be able to enter a decimal as the first value). Then we make sure the value in the input area isn't 0 (zero), this we will handle later.

If all those are true then we enter the decimal then toggle the

**hasDecimal**to True, so the user cant enter a 2nd one. Now, if the input area doesn't have a value, we enter 0., as we assume the user is wanting to work with a decimal value such as 0.5. Lets take a look at the procedure for doing this:

private void cmdDecimal_Click(object sender, System.EventArgs e) { //Check for input status (we want true) if (inputStatus) { //Check if it already has a decimal (if it does then do nothing) if (!hasDecimal) { //Check to make sure the length is > than 1 //Dont want user to add decimal as first character if (txtInput.Text.Length != 0) { //Make sure 0 isnt the first number if (txtInput.Text != "0") { //It met all our requirements so add the zero txtInput.Text += cmdDecimal.Text; //Toggle the flag to true (only 1 decimal per calculation) hasDecimal = true; } } else { //Since the length isnt > 1 //make the text 0. txtInput.Text = "0."; } } } }

As you can see, we check all the items mentioned above, if they're True we add the decimal, otherwise we add 0. to the input area.

The first calculation we will look at is addition. The first thing we do here is to make sure the input box has a value (Length > 1). If it does then we check the

**calcFunc**value.

*The calcFunction variable will be used to tell our*. Here, if the value is empty (String.Empty) we assign the value of our input box to a variable,

**CalculateTotals**procedure which calculation to perform**valHolder1**, which will hold the first part of all calculations, then clear out the input box so the user can enter a 2nd number.

If the

**calcFunc**variable isnt empty then we call our

**CalculateTotals**procedure to display a total to the user. We then assign the value of

*Add*to our variable for the next turn through, then we toggle the

**hasDecimal**flag to False. Now lets take a look at how we accomplished this:

private void cmdAdd_Click(object sender, System.EventArgs e) { //Make sure out input box has a value if (txtInput.Text.Length != 0) { //Check the value of our function flag if (calcFunc == string.Empty) { //Flag is empty //Assign the value in our input //box to our holder valHolder1 = System.Double.Parse(txtInput.Text); //Empty the input box txtInput.Text = string.Empty; } else { //Flag isnt empty //Call our calculate totals method CalculateTotals(); } //Assign a value to our calc function flag calcFunc = "Add"; //Toggle the decimal flag hasDecimal = false; } }

Believe it or not, all the other basic calculation buttons are the same as the Add button, with the exception of what we set

**calcFunc**to. In the other buttons we set this variable to the calculation we want to perform, Subtract,

Divide, Multiply, and so on, so there really isn't a reason to show how that is done since we did the Add button and the others are the same.

Even though they are the same I'll show the functionality of one more calculation button. This time we will look at the code for the subtraction button. The first thing we do here is to make sure the input box has a value (Length > 1). If it does then we check the

**calcFunc**value.

*The calcFunction variable will be used to tell our*. Here, if the value is empty (String.Empty) we assign the value of our input box to a variable,

**CalculateTotals**procedure which calculation to perform**valHolder1**, which will hold the first part of all calculations, then clear out the input box so the user can enter a 2nd number.

If our

**calcFunction**isnt empty then we call our

**CalculateTotals**method to perform the calculations. We then assign the value of

**Subtract**to our

**calcFunc**variable so the calculations method will know which calculation to perform. The code for the subtraction button looks like this:

private void cmdSubtract_Click(object sender, System.EventArgs e) { //Make sure the input box has a value if (txtInput.Text.Length != 0) { //Check the valueof our calculate function flag if (calcFunc == string.Empty) { //Flag is empty //Assign the value of our input //box to our holder valHolder1 = System.Double.Parse(txtInput.Text); //Empty the input box txtInput.Text = string.Empty; } else { //Flag isnt empty //Call our calculate totals method CalculateTotals(); } //assign a value to our //calculate function flag calcFunc = "Subtract"; //Toggle the decimal flag hasDecimal = false; } }

Thats how the normal calculation buttons are coded. Now lets say you want to give the user the option to calculate Exponents, 4^2 for example. To code this button you need a couple of checks before doing anything. First we need to check and make sure the input area has a value, if it does then we check to see the value of the

**calcFunc**variable.

If this is empty, we then convert the value of the input area to a Double and assign it to the

**valHolder1**variable to hold on to, this will be used for the calculations in the

**CalculateTotals**procedure and empth the value from the input area.. If its not empty we directly call the

**CalculateTotals**function as this means the user has already entered 2 numbers.

We then assign the value of

*PowerOf*to our

**calcFunc**variable, this will tell CalculateTotals what calculation to perform, and toggle the

**hasDecimal**flag to False. Lets take a look at how we accomplished all of this:

private void cmdPowerOf_Click(object sender, System.EventArgs e) { //Make sure the input box has a value if (txtInput.Text.Length != 0) { //Check if the calcFunc flag is empty if (calcFunc == string.Empty) { //Assign the value of the input box to our variable valHolder1 = System.Double.Parse(txtInput.Text); //Empty the input box //So the user can enter the power of value txtInput.Text = string.Empty; } else { //Call the calculate totals method CalculateTotals(); } //Assign our flag the value of "PowerOf" calcFunc = "PowerOf"; //Reset the decimal flag hasDecimal = false; } }

Doing a Square Root is somewhat different as it doesn't take 2 values, just the number you want the square root of, so some of the checking required in the other calculations isn't required here. For a Square Root we first check to ensure the input area has a value. If it does have a value we assign the value of the input area, converted to a Double, to our

**tmpValue**variable.

Once we have the value, we call the System.Math.Sqrt Method to perform the calculations on the

**tmpValue**variable. Once this is complete we assign the resulting value to our input area, then toggle the

**hasDecimal**flag to False. Lets take a look at how this is done:

The Equals button is quite simple. Here, we first check to make sure our input area has a value and that our

**valHolder1**variable isn't a zero (Divide by 0 is a bad thing). If both of these are true we call the

**CalculateTotals**procedure to perform our calculations based on the value of the

**calcFunc**flag. We then clear the value of

**calcFunc**and toggle the

**hasDecimal**flag to False. This is done like this:

private void cmdSqrRoot_Click(object sender, System.EventArgs e) { //Make sure the input box has a value if (txtInput.Text.Length != 0) { //Assign our variable the value in the input box tmpValue = System.Double.Parse(txtInput.Text); //Perform the square root tmpValue = System.Math.Sqrt(tmpValue); //Display the results in the input box txtInput.Text = tmpValue.ToString(); //Clear the decimal flag hasDecimal = false; } }

In the last 2 buttons we have looked at how you use the two System.Math Members I mentioned earlier, pretty simple isnt it.

We have 3 more buttons to look at before we look at the

**CalculateTotals**procedure. First we'll look at the backspace button.For the backspace, first we need to make sure the input are has a value. If it does then we retrieve the next to last character and see if its a decimal, if it is we toggle the

**hasDecimal**flag to False. Next we create an Integer variable (

**loc**) to hold the length of the contents in the input area. From there we use

**Remove**, along with

**loc**to remove the last character of the string for each time the user clicks the backspace button.

private void cmdBackspace_Click(object sender, System.EventArgs e) { //Declare locals needed string str; int loc; //Make sure the text length is > 1 if (txtInput.Text.Length > 0) { //Get the next to last character str = txtInput.Text.Substring(txtInput.Text.Length - 1); //Check if its a decimal if (str == ".") { //If it is toggle the hasDecimal flag hasDecimal = false; } //Get the length of the string loc = txtInput.Text.Length; //Remove the last character, incrementing by 1 txtInput.Text = txtInput.Text.Remove(loc - 1, 1); } }

The last 2 buttons I'm going to demonstrate are the CE (Clear entry) and C (Clear all) buttons. These are very simple. First the clear entry button. What we do here is set the value in the input area to empty (String.Empty), and the

**hasDecimal**flag to false.

private void cmdClearEntry_Click(object sender, System.EventArgs e) { //Empty the input box txtInput.Text = string.Empty; //Toggle the decimal flag hasDecimal = false; }

The clear all button required a bit more code as we do more with this button. Here we set our 2 holder variables,

**valHolder1**and

**valHolder2**to 0 (zero), we then set the

**calcFunc**flag to String.Empty and the

**hasDecimal**flag to False, like this:

private void cmdClearAll_Click(object sender, System.EventArgs e) { //Empty the text in the input box txtInput.Text = string.Empty; //Clear out both temp values valHolder1 = 0; valHolder2 = 0; //Set the calc switch to empty calcFunc = string.Empty; //Toggle the hasDecimal flag hasDecimal = false; }

Those are the buttons you need for a

*Basic*calculator. The final thing we're going to look at is the procedure that actually does the calculations,

**CalculateTotals**. Here the first thing we do is set our variable

**valHolder2**to the current value of the input area.

We then do a switch(calcFunc) on the value of

**calcFunc**so we know which calculations to perform. We perform our calculations (add, subtract, divide, multiply, exponent, etc) and set the results to the input area so the user can see their results. Finally we set the

**inputEntry**flag to False. This is what this procedure looks like:

private void CalculateTotals() { valHolder2 = System.Double.Parse(txtInput.Text); //determine which calculation we're going to execute //by checking the value of calcFunc switch (calcFunc) { //addition case "Add": valHolder1 = valHolder1 + valHolder2; break; //subtraction case "Subtract": valHolder1 = valHolder1 - valHolder2; break; //division case "Divide": valHolder1 = valHolder1 / valHolder2; break; //multiplication case "Multiply": valHolder1 = valHolder1 * valHolder2; break; //exponents (power of) case "PowerOf": valHolder1 = System.Math.Pow(valHolder1, valHolder2); break; } //set our input area to the value of the calculation txtInput.Text = valHolder1.ToString(); inputStatus = false; }

**NOTE:**For the Exponents (Power Of) we use the System.Math.Pow Method for calculating the value.

There are two more buttons in this calculator that we didn't cover, basically due to the length of the tutorial. Those buttons are included in the sample project I'm attaching to this tutorial.

Thats it, thats how you create a basic calculator in C#. I hope you find this tutorial helpful. I am including the project file with this tutorial, but remember this solution is under the

**GNU GENERAL PUBLIC LICENSE**so you may not remove the header from the files or turn this project in as your homework assignment.

I know I am forced to go with the

*honor system*in this, but if you do just turn this in as your assignment not only will you be cheating, but you will learn nothing, and subsequently wont know enough to become a programmer once you get out of school.

I will be doing a 2nd part to this tutorial where I look at adding more advanced functionality to this calculator, such

as adding a number to memory, removing a number from memory, calculations with a number in memory and more.

Thank you for reading!

PC_Calculator_CSharp.zip

**(120.99K)**

Number of downloads: 18475