Simple Calculator in C#



This section is for the programmers who are just starting with C#.This Calculator does addition, subtraction, multiplication and division.If u try to launch calculator by running calc from Run window.You will get an Idea, how a calculator works.Here i have tried to recreate Windows calculator with the help of c# Language.

Before we get to the code, let’s just go through how our calculator is going to work:

1.Click the number buttons. This will be the first number in the addition
2.The first number you want to add will then appear in the text box
3.Click the Plus button to tell the calculator you want to add
4.The first number will disappear from the text box, ready for the second number
5.Click the number buttons again to add the second number
6.Click the equals button and the answer appears in the text box

So the First step is When we press the numbers in the calculator, it need to be displayed in the text box.


Code Snippet

 void digitButton_Click(object sender, EventArgs e)
        {
            Button ButtonThatWasPushed = (Button)sender;
            txtResult.Text += ButtonThatWasPushed.Text;

        }

The typical signature of an event handler is void EventHandler(object sender, EventArgs e). sender is the object that fired the event. In the case of a Button’s click event, the sender will be that Button.
Again we need to add this event handler in the page load event.

Code Snippet


 btn0.Click += new EventHandler(digitButton_Click);
            btn1.Click += new EventHandler(digitButton_Click);
            btn2.Click += new EventHandler(digitButton_Click);
            btn3.Click += new EventHandler(digitButton_Click);
            btn4.Click += new EventHandler(digitButton_Click);
            btn5.Click += new EventHandler(digitButton_Click);
            btn6.Click += new EventHandler(digitButton_Click);
            btn7.Click += new EventHandler(digitButton_Click);
            btn8.Click += new EventHandler(digitButton_Click);
            btn9.Click += new EventHandler(digitButton_Click);

The next step is doing manipulations ,Ie addition, multiplication etc

Code Snippet

 void digitCalculate_Click(object sender, EventArgs e)
        {
            Button ButtonThatWasPushed = (Button)sender;
            string ButtonText = ButtonThatWasPushed.Text;
           
       if (txtResult.Text != string.Empty)
            {
                double valueHolder1 = Convert.ToDouble(txtResult.Text);
            }
            if (ButtonText == "+")
            {
                Result = txtResult.Text;
                CheckForManipulation = "Add";
                txtResult.Clear();
                txtResult.Focus();


            }
            else if (ButtonText == "-")
            {
                Result = txtResult.Text;
                CheckForManipulation = "Substract";
                txtResult.Clear();
                txtResult.Focus();


            }
            else if (ButtonText == "*")
            {
                Result = txtResult.Text;
                CheckForManipulation = "Multiply";
                txtResult.Clear();
                txtResult.Focus();

            }
            else if (ButtonText == "/")
            {
               
                Result = txtResult.Text;
                CheckForManipulation = "Division";
                txtResult.Clear();
                txtResult.Focus();
            
            }
 if (ButtonText == "MC")
            {
                //Memory Clear
                this.MemoryStore = 0;
                return;
            }

            if (ButtonText == "MR")
            {
                //Memory Recall
                txtResult.Text = this.MemoryStore.ToString();
                return;
            }

            if (ButtonText == "MS")
            {
                // Memory subtract
                this.MemoryStore -= Convert.ToDecimal(this.EndResult);
                return;
            }

            if (ButtonText == "M+")
            {
                // Memory add 

                this.MemoryStore += Convert.ToDecimal(this.EndResult);
                return;

            }

        }

We need to add this event handler just like we ve done before


Code Snippet

 btnPlus.Click += new EventHandler(digitCalculate_Click);
            btnMinus.Click += new EventHandler(digitCalculate_Click);
            btnMult.Click += new EventHandler(digitCalculate_Click);
            btnDiv.Click += new EventHandler(digitCalculate_Click);

on clicking the equal button we need to show the result in the text box

Code Snippet

          private void btnEqual_Click(object sender, EventArgs e)
        {

            if (txtResult.Text != string.Empty && Result != string.Empty)
            {
               double valueHolder2 = Convert.ToDouble(txtResult.Text);
               double chk = Convert.ToDouble(Result);
               if (CheckForManipulation == "Add")
               {

                   EndResult = chk + valueHolder2;
                   txtResult.Text = EndResult.ToString();

               }
               else if (CheckForManipulation == "Substract")
               {

                    EndResult = chk - valueHolder2;
                   txtResult.Text = EndResult.ToString();
               }
               else if (CheckForManipulation == "Multiply")
               {
                   
                 EndResult = chk * valueHolder2;
                   txtResult.Text = EndResult.ToString();
               }
               else if (CheckForManipulation == "Division")
               {
                   
                   if (valueHolder2 == 0)
                   {
                       txtResult.Text = "Cannot divide by Zero";
                       return;
                   }
                    EndResult = chk / valueHolder2;
                   txtResult.Text = EndResult.ToString();
            }
          
            }
        }

For the rest of the manipulations, we use the code below

Code Snippet

  private void btnpoint_Click(object sender, EventArgs e)
        {
         if (txtResult.Text.Contains("."))
            {
                txtResult.Text = txtResult.Text;
            }

            else
            {
                txtResult.Text = txtResult.Text + ".";
            }

        }
         private void btnReciprocal_Click(object sender, EventArgs e)
        {
            //To find the reciprocal 
            if (txtResult.Text != string.Empty)
            {

                double chk = Convert.ToDouble("1") / Convert.ToDouble(txtResult.Text);
                txtResult.Text = chk.ToString();
              
            }

        }
         private void btnPlusMinus_Click(object sender, EventArgs e)
        {   
            //To find the Inverse
            if (txtResult.Text != string.Empty)
            {
                double chk = Convert.ToDouble(this.txtResult.Text);
                chk = -chk;
                txtResult.Text = chk.ToString();
            }

        }

       private void btnSqrt_Click(object sender, EventArgs e)
        {
            //To find the Square root
            if (txtResult.Text != string.Empty)
            {
                double SqrRoot = Math.Sqrt(Convert.ToDouble(this.txtResult.Text));
                txtResult.Text = SqrRoot.ToString();
            }
        }
private void btnClear_Click(object sender, EventArgs e)
        {
            // to clear the Content
                txtResult.Clear();
                txtResult.Focus();

        }

        private void btnBackspace_Click(object sender, EventArgs e)
        {
            //backspace
            if (txtResult.Text != string.Empty)
            {
                int txtlength=txtResult.Text.Length;
                if (txtlength != 1)
                {
                    txtResult.Text = txtResult.Text.Remove(txtlength - 1);
                }
                else
                {
                    txtResult.Text = 0.ToString();
                }
               
            }

        }
    }

Please Find the Whole Code Download source code
HappyCoding ! πŸ˜‰

Advertisements

29 responses to this post.

  1. the good thing about geek girl is that she is organized πŸ™‚

    Reply

  2. Posted by T2P on August 14, 2011 at 4:51 AM

    Thank you for the help.What is the CheckForManipulation variable?Where is it declared.I am getting errors pertaining to it.Please help me

    Reply

  3. Posted by T2P on August 14, 2011 at 4:55 AM

    Thank you for the help.What is the CheckForManipulation variable and the Result variable?Where are the two declared.I am getting errors pertaining to them.Please help me

    Reply

  4. T2P,
    declare CheckForManipulation and Result variable as global variables
    ie,
    string Result;
    string CheckForManipulation;
    Then your problem will be solved.

    Reply

  5. Posted by srav on January 5, 2012 at 1:33 AM

    Thanks.. Really Helpful….

    Reply

  6. Posted by Johnny on March 2, 2012 at 7:58 PM

    What are the MC MR MS and M+ buttons for? With the code that you have there is no button to clear the calculator to start again. Also my add button does not work. When I click on that button an error message comes up saying “input string was not in a correct format”. Finally, the divide and multiply buttons work but the divide and add buttons do not. Any pointers about where I might have gone wrong. I have gone over the code many times and it seems all correct.

    Reply

  7. Posted by Johnny on March 2, 2012 at 8:15 PM

    Need to be more careful. Have found minor spelling errors that have caused the problems. So just interested in what the MC MR MS and M+ buttons are for?

    Reply

  8. Posted by odeon on March 5, 2012 at 5:01 AM

    Hi,

    If a user presses the decimal point twice. How will it be handled?

    Reply

    • Hi Odeon,
      Thanks for visiting my blog and commenting here.
      I’ ve made Couple of changes.They’re summarized below

      1.Add a bool(Check)flag

      2. initialize it to false

      3.If a decimal is entered, check the flag, if it is false, accept it and set the flag to True

      4.If a decimal is entered and the flag is True, don’t accept it.

      5.Whenever you press an operand, set this flag back to False.

      Reply

      • Hi i ve find a better solution to this .

        The “contains” method can be used if you want to check if a string contains certain characters.
        It’s fairly simple to use.

        So i replaced the code as

        if (txtResult.Text.Contains(“.”))
        {
        txtResult.Text = txtResult.Text;
        }

        else
        {
        txtResult.Text = txtResult.Text + “.”;
        }

        Hope this clears your doubt!

  9. Thanks for dropping by and commenting everybody…

    Please find the complete source code in the link given below

    calculatorJune01

    Thank you once again and have a great day. πŸ™‚

    Reply

  10. Posted by Mr.Hitch on May 1, 2012 at 6:52 PM

    Hi ! why whn I try to compile your code. The compiler always give me this response:
    ‘Calculater.Calculator’ does not contain a definition for ‘txtResult’ and no extension method ‘txtResult’ accepting a first argument of type ‘Calculater.Calculator’ could be found (are you missing a using directive or an assembly reference?)

    Reply

  11. Posted by Domo on May 9, 2012 at 6:01 PM

    Hey, I’ve Gone over the code, but when i run it, it doesn’t clear the textbox on my button clicks.. it crashes when = is clicked… same as above ” input string…..” am i missing something?

    Reply

  12. Hi All,

    I m back.I ve modified the source code.

    With this update not only are some bugs fixed, but few new features are also added

    The features added to it are

    1.Backspace

    2.Clear

    3.MC(Memory Clear)

    4.MR(Memory Recall)

    5.MS( Memory subtract)

    6.M+(Memory add )

    Please find the complete source code in the link given below

    https://soumiaw.files.wordpress.com/2012/06/calculatorjune01.docx

    Thank you once again and have a great day.

    Reply

  13. Posted by depth on January 18, 2013 at 10:09 PM

    I tried the above code . If I try to add two decimal number like(1.2+1.2) it doesnt give answer 2.4 .It gives result as 24. Please suggest me how to write logic of the same.
    Thanks in advanced . I am beginner I stuck from two days .but couldnt find any solution . Please help me guys

    Reply

  14. Posted by Ravnish on February 17, 2013 at 11:05 AM

    Thank you ….But if anyone can email me the coding and the application because i have tried with mt own and im having problems. I mean the whole thing done is Visual Studio.
    Regards.

    Reply

  15. Awesome, thanks! I appreciate that you left a few things out of the source, as it forced me to figured out a bit more. Successfully built a working calculator after using Visual Studio for 5 minutes before. πŸ˜€

    Reply

  16. Posted by murique on March 7, 2014 at 9:04 PM

    Hey

    Can someone please help me I have to make a simple calculator but I’m only allow to use: if statements, arrays and variables…

    Reply

  17. Posted by Bitron on June 10, 2015 at 6:08 PM

    There is no percentage I think I can’t find it…
    The code is one of the best someone could possibly use!!!

    Reply

  18. Posted by Bitron on June 10, 2015 at 8:08 PM

    I couldn’t find it in the code so I coded it my self.

    I think that can work :
    peivate void BtnPercent_Click(object sender, evender, EventArgs e)
    {
    Double valueHolder3 = Convert.ToDouble(txtResult.Text);
    Double chk2 = Convert.ToDouble(Result);
    {
    EndResult = valueHolder3 * chi / 100;
    txtResult.Text = EndEesult.ToString();
    }

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: