Thursday, August 18, 2011

Calculator

Hi guys. This is the first full fledged application i made using c# on MS visual studio 2008.

This is also the first application on which i tried setup and deployment. If you have any doubts on the logic in the coding, please mail me at nardz07@gmail.com.

Here's the basic cs code for you:



Firstly all the packages are added:

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;

We initialise the store value numeric variables and the flags that will be used in different places

namespace calculator
{
    public partial class Calculate : Form
    {
        double a, b, c, z;
        char math_pros;
        int count = 0;
        private bool hasDecimal = false;

        public Calculate()
        {
            InitializeComponent();
        }

Above, a and b are store value variables, while c is the variable that stores the final answer. Z is the variable that is used for all the temporary or intermediate value storing.
math_pros is a flag to tell us which function (+,-,*,/) is impending.
Count is a flag which tells how many instructions have been made in a single computational string.
hasDecimal is a flag that tells if the number has a decimal sign on it or not.

We must first initialise the numbers 0 to 9. this is simply done via the following coding:

private void btn1_Click(object sender, EventArgs e)
        {
            tb.Text = tb.Text + btn1.Text.ToString();
        }

This adds the button value (in this case: 1) to the text box value already existing, say 23. this is shown below:






Once we have set similar coding for all the digits, we can now try out simple sums like addition:

private void btnadd_Click(object sender, EventArgs e)
        {
            hasDecimal = false;

            if (count == 0)
            {
                double.TryParse(tb.Text, out a);

                tb.Clear();
                tb.Focus();
                count = 1;
            }


Whenever we press any button, be it + or -, the textbox must clear after storing the value for the next operation. So, the decimal point must be nullified. Hence we set hasDecimal to false.

Now, if the clicking of the addition button is the first action, then the number in the text box must be stored in 'a'.

If not, it means some other button has been clicked already. It should run that function and save its value before accepting the addition command. Hence, here it checks the different states for math_pros and runs the corresponding function as shown below:

else
            {
                if (math_pros == 'd')
                {
                    div();
                }
                if (math_pros == 'm')
                {
                    mul();
                }
                if (math_pros == 's')
                {
                    sub();
                }
                if (math_pros == 'a')
                {
                    add();
                }
                if (math_pros == 'p')
                {
                    per();
                }
                if (math_pros == 'e')
                {
                    exp();
                }
            }

            math_pros = 'a';

        }


At the end of the else statement, we change the value of the flag to 'a', for add.

The other values are

s = subtract

m = multiply

d = divide

p = percentage

e = exponential

The same logic is used for the subtraction, multiplication, division, percentage and exponential buttons. Now let us see what happens in the functions, as we cannot store the text value into 'a' once count is more than 0.

since we have already seen addition i'll show the subtraction and percentage functions here:

 public void sub()
        {
            double.TryParse(tb.Text, out z);
            a = a - z;
            count++;
            tb.Clear();
            tb.Focus();
        }

        public void per()
        {
            double.TryParse(tb.Text, out z);
            a = ((a / z) * 100);
            count++;
            tb.Clear();
            tb.Focus();
        }


Here, we store the present value of the text box in a temporary variable z, and then append, subtract, multiple, divide from/to the original value stored in 'a' and store the result back in 'a'. Then we increment count and clear the text box again.

This way however many functions we keep using before our ultimate = it keeps calculating and storing the value in 'a'.

Now, when we press the = button, the textbox value should be stored in 'b' and the previous math_pros be solved with 'a' and 'b' and stored in 'c'. We then present the 'c' to the user. All the memory values are then cleared and the flags are reset to their default values.

private void btnequals_Click(object sender, EventArgs e)
        {
            double.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;
            }
            if (math_pros == 'e')
            {
                c = System.Math.Pow( a , b );
            }
            if (math_pros == 'p')
            {
                c = ((a / b) * 100);
            }

            tb.Text = (c.ToString());
            c = 0;
            b = 0;
            z = 0;
            hasDecimal = false;
            count = 0;
        }

The CLEAR (C) button clears all memory values and resets the flag completely. The CLEAR ENTRY (CE) button simply clears the textbox but retains the memory values and flags.

The Square root, negative, and reciprocal buttons are also pretty straightforward as they take the value from the textbox and operate directly on them. They do not require any memory space at all.

The next most interesting button is the decimal button.

This button must first check if the hasDecimal flag is negative, because only if there is no '.' in the textbox it can function. Once a decimal dot has been put, it must not allow another, so the flag must be turned on on the first press.
Next it must check if the textbox is empty. If it is, it should add a 0 before the'.', otherwise simply append the '.' button.

if (!hasDecimal)
            {
                if (tb.Text.Length != 0)
                {
                   
                        tb.Text += btndot.Text;
                        hasDecimal = true;
                }
                else
                {
                    tb.Text = "0.";
                    hasDecimal = true;
                }
            }

Also there is the back button, in case the user puts in a wrong value. For this,

private void btnback_Click(object sender, EventArgs e)
        {
            string str;
            int loc;
            if (tb.Text.Length > 0)
            {
                str = tb.Text.Substring(tb.Text.Length - 1);
                if (str == ".")
                {
                    hasDecimal = false;
                }
                loc = tb.Text.Length;
                tb.Text = tb.Text.Remove(loc - 1, 1);
            }
        }

It checks the length and then removes the last entered value from it. It also must allow for a way to make the hasDecimal back to false in case the '.' is removed.

This should allow for the perfect functionality of this calculator.

In case of any doubts or suggestions, please comment on this post, or ask me personally at the aforementioned email id.

1 comment: