C#- simple calculator for C# | basic calculator program using C# language

 

     C# - Simple Calculator?




Body
In this tutorial, we will create a Simple Calculator using C#. C# is a general-purpose, object-oriented programming language. C# is expected to make it faster and less expensive to develop new applications. The potential of C# is great when it comes to developing desktop applications. It has a friendly environment for all new developers. So let's do the coding.

Getting Started

First, you will have to download & install Visual Studio. Visual Studios is an open-source development feel free to create any application that you want. Here's the link for the Visual Studio https://www.visualstudio.com/

Application Design

We will now create the design for the application, first, locate the designer file called form1.Designer. cs, this is the default name when you create a new windows form. Then write these codes inside your designer file.


To create a calculator program in C#, you need to use WebForms. Under that create buttons from 1-9, addition, subtraction, multiplication, etc.

Let us see the code for addition, subtraction, and multiplication. Firstly, we have declared two variables −

static float x, y;

Now, we will see how to set codes for calculation on individual button click: Our result textbox is tbResult since we have used Windows Form as well to display the calculator −

protected void add_Click(object sender, EventArgs e) {
   x = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   y = '+';
   tbResult.Text += y;
}
protected void sub_Click(object sender, EventArgs e) {
   x = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   y = '-';
   tbResult.Text += y;
}
protected void mul_Click(object sender, EventArgs e) {
   x = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   y = '*';
   tbResult.Text += y;
}

The following is the equal button code −

protected void eql_Click(object sender, EventArgs e) {
   z = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   if (y == '/') {
      p = x / z;
      tbResult.Text += p;
      x = d;
   } else if (y == '+') {
      p = x + z;
      tbResult.Text += p;
      a = d;
   } else if (y == '-') {
      p = x - z;
      tbResult.Text += p;
      x = p;
   } else {
      p = x * z;
      tbResult.Text += p;
      x = p;
   }
}

Recommended Articles

This is a guide to C#- simple calculator . Here we discuss the basic concept different examples and code implementation. You may also look at the following articles to learn more –

Post a Comment

3 Comments