c#: Building a Basic Calculator Program

Author: Ronald S. Holland
at
Total Application Works

ronholland@sumtotalz.com






To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript c#


To contact us

2002 - 2013 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file or send this page to a friend.)
  • <html>
    <title>Example of a link </title>
    <body>
    <table border width=65%>
    <a
    href="http://www.sumtotalz.com/TotalAppsWorks/CSharp/CS_BasicCalc_Tut_III.html">How to Create a Basic Calculator III Application </a>
    </table>
    </body>
    </html>
    Source
    Screenshot
    On-site classes can be arranged in Java and C++. Send all inquiries to:
    RonHolland@sumtotalz.com


Read Me First

The Basic_Calc.zip compressed file contains the following seven projects:

  1. Basic_Calc.cs
  2. Basic_Calc.MS VS Solution
  3. Basic_Calc.Designer.cs
  4. Program.cs
  5. Basic_Calc.SLN
  6. Basic_Calc.zip
  7. CS_BasicCalc_Help.html
  8. CS_BasicCalc_Tut.html
To run the project:
  1. Go to the folder where you downloaded the Basic_Calc.zip compressed file
  2. Extract the files
  3. Right clck on one of the Basic_Calc.MS VS Solution ( Microsof Visual studio Solution - click on the version of Microsoft studio you have
  4. When Microsoft studio IDE is started
  5. Click on theDebug menu
  6. Click on theStart without Debugging menu item
    • The Basic_Calc.MS VS Solution will begin to execute
  7. To modify the Basic_Calc GUI
    1. Click on the View tab
    2. Select Solution Explorer
      • This will cause a Solution Explorer window to open
    3. Doubl-click on Basic_Calc.cs
      • This will cause the Basic_Calc.cs {Design] window to open, displaying Basic_Calc GUI

Introduction

This tutorial is intended for people who have some experience with java, c++, or c#. In this example, we will build a c# basic calculator application. In order for you to follow this tutorial, you will need a copy of the Microsoft c# compiler. In addition, this tutorial assumes that you have worked through the following tutorials:

  1. Introduction to c#
  2. Introduction to c# Forms
  3. Introduction to c# Event Handling
After working through the above tutorials, especially the one on Introduction to c# Forms, and the MS Visual Studio IDE you should be able to develop files similar to:
  1. Basic_Calc.cs - an event handler that responds to button mouse click events.
  2. Basic_Calc.Designer.cs - GUI layout/design manager.
    • You can add a line similar to the following to change the font-size.
    • this.btnPoint.Font = new System.Drawing.Font("Arial", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  3. Program.cs - The main entry point for the application when it is loaded into memory.

In the next section, we will list the requirements for building this calculator.

Requirements

The requirements for the task are:

  1. Build a calculator application, using the Form class.
  2. Build a five-function calculator with the following functions:
    • Back - behaves like backspace
    • Copy - copies to clipboard
    • Addition - adds two numbers: n1 + n2.
    • Subtraction - subtracts number two from number one: n1 - n2.
    • Multiplication - Multiplies two numbers: n1 * n2.
    • Division - divides number two into number one: n1 / n2.
    • SQR - provides the square of a number (x * x).
    • SQRT - provides the square root of a number n1 .
    • Provide minimal error checking, in order to keep the code less complex.
  3. Use PushButtons for the numbers, functions, Exit, Help, and About.
  4. Create an event handler to respond to the events caused by the PushButtons used for numbers, functions, Exit, Help, and About buttons.
  5. Use the Building the MS Visual Studio Basic Application Template as the basis for building this application.
  6. The calculator should look something like the following:
     
    
    GUI Comments
                       765.9
    <------------- Input box
     
    Back
     
    Copy
     
    7 8 9 / Clear
    4 5 6 X Sqr
    1 2 3 - SQRT <------ Buttons x2
    +/- 0 . + = cause events
      
    Help
      
    About OFF when clicked
    Figure 1: Basic Calculator
  7. Use Holland's OOP Programming Design Model to build this calculator.

What is the Holland's OOP Programming Design Model?

In object-oriented programming, programming revolves around the data. So in this style, the top is the data. It might be depicted as follows:

  
          +--------------+
          |      Data    |<----+  
          +-------+------+     | 
                  ^            |
                  |----------->+
                  V            ^
          +-------+------+     |
          |   Top-down   |     | 
          |  Structured  |<----+
          |  programming |     |
          |  on Classes  |     | (step-wise)
          |  and methods |     | (refinement)
          +--------------+     | (as needed) 
                  |            |
                  +------------+ 
 
  
Figure 2: Holland's OOP Programming Design Model


The data is entered in the Display box on the calculator, using the pushbuttons with numbers and/or a dot on it. This data is operated on in a binary (two numbers) fashion or in a unary (one number) fashion. The calculator operates in a

  1. binary (two numbers)
    • Multiplication
    • Division
    • Subtraction
    • Addition
  2. unary (one number) fashion
    • SQRT
    • Plus/Minus
  3. Application functions
    • Clear
    • Back
    • OFF
  4. Equals sign displays the result of binary and/or unary operations.
  5. The pressing of the pushbuttons will result in a Mouse click event handler (method) responding to the event.
    • Clear Clicked
    • Plus Clicked
    • Minus Clicked
    • Mult Clicked
    • Div Clicked
    • SQRT Clicked
    • OFF Clicked
    • Help Clicked
    • About Clicked
In the next section, I will describe how to build the calculator template.

Building the MS Visual Studio Basic Application Template

How do we go about Building the MS Visual Studio Basic Application Template? The MS Visual Studio Application Template consists of three components, which are:

  1. Basic_Calc.cs - an event handler that responds to button mouse click events.
  2. Basic_Calc.Designer.cs - GUI layout/design manager.
  3. Program.cs - The main entry point for the application when it is loaded into memory.
An outline for these three components is:

   
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Calculator
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Calculator());
        }
    }
}
  
Figure 3: Program.cs - Main method

   
namespace Basic_Calc
{
    partial class Basic_Calc
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be 
        /// disposed; 
        ///   otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager 
                  resources = new    
          System.ComponentModel.ComponentResourceManager
                 (typeof(Calculator));
            this.Displaylbl = new System.Windows.Forms.Label();
            this.btnPoint = new System.Windows.Forms.Button();
            this.btn0 = new System.Windows.Forms.Button();
            this.btn1 = new System.Windows.Forms.Button();
                     . . .
            this.SuspendLayout();
            // 
            // Displaylbl
            // 

            // 
            // btnPoint
            // 

            // 
            // btn0
            //

            // 
            // btn1
            // 

            // 
            // btn2
            // 

            // 
            // btn3
            // 

            // 
            // btn4
            // 

            // 
            // btn5
            // 

            // 
            // btn6
            // 

            // 
            // btn7
            // 

            // 
            // btn8
            // 

            // 
            // btn9
            // 

            // 
            // btnEqual
            // 

            // 
            // btnMinus
            // 

            // 
            // btnMultiply
            // 

            // 
            // btnDivide
            // 

            // 
            // btnClear
            // 

            // 
            // btnPlus
            // 

            // 
            // btnPlusMinus
            // 

            // 
            // bSquare
            //

            // 
            // btnBack
            // 

            // 
            // btnOFF
            //  

            // 
            // bCopy
            // 

            // 
            // btnabout
            // 

            // 
            // btnHelp
            // 

            // 
            // Calculator add buttons to Form
            // 

        }

        #endregion

        private System.Windows.Forms.Label Displaylbl;
        private System.Windows.Forms.Button btnPoint;
                    ...
        private System.Windows.Forms.Button btnHelp;
    }
}
};
  
Code snippets
  

// 
// btnPoint
//                                                 Font  Size
//                                                      | 
//                                                      v 
this.btnPoint.Font = new System.Drawing.Font("Arial", 15.75F, 
                     System.Drawing.FontStyle.Bold, 
                     System.Drawing.GraphicsUnit.Point, 
                             ((byte)(0)));
this.btnPoint.Location = new System.Drawing.Point(167, 242);
this.btnPoint.Name = "btnPoint";
this.btnPoint.Size = new System.Drawing.Size(55, 33);
this.btnPoint.TabIndex = 0;
this.btnPoint.TabStop = false;
this.btnPoint.Text = ".";
this.btnPoint.UseVisualStyleBackColor = true;
  // event handler 

//......................................................


// 
// btnOFF
// 
this.btnOFF.BackColor = System.Drawing.Color.Red;
this.btnOFF.Font = new System.Drawing.Font("Arial", 15.75F, 
                   System.Drawing.FontStyle.Bold, 
                   System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnOFF.Location = new System.Drawing.Point(275, 295);
this.btnOFF.Name = "btnOFF";
this.btnOFF.Size = new System.Drawing.Size(67, 33);
this.btnOFF.TabIndex = 1;
this.btnOFF.TabStop = false;
this.btnOFF.Text = "OFF";
this.btnOFF.UseVisualStyleBackColor = false;
 // event handler 
 
Figure 4: Basic_Calc.Designer.cs - GUI Layout

For those who are familiar with Java's event handler, you will see similar code in Figure 5, Figure 6 and Figure 7.

   
   /**  *********************************************************
    * The actionPerformed() method is the method that is called to
    * respond to a button event.
    * ************************************************************/
   public void actionPerformed( ActionEvent e )    {

      tempNum = ""  + answer ;

      if ( e.getSource() == bPlus || e.getSource() == bSub ||
              e.getSource() == bMult || e.getSource() == bDiv  ) {
         tempNum = ""  + answer ;

         MyPrint( "actionPerformed() 1a: The value of result is " + 
             result + " The value of tempNum is " + 
             enterBox.getText() +
                " The value of opCode is " + opCode ) ;
      }

  
Figure 5: Code snippet for Java event handler


In this next table, we will outline the code that responds to a button control being clicked.

   
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;
using System.Diagnostics;
using System.ComponentModel;

namespace Calculator
{
    public partial class Calculator : Form
    {
        char  oper = ' ';
        double num2 = 0, num1 = 0, num3 = 0;
        bool equal = false;
        bool percent = false;

        public Calculator()
        {
            InitializeComponent();
        }

/*********************************************************
 * onClick() is an event handler that responds to mouse 
 * click events.
 ********************************************************/
private void onClick(object event_key, EventArgs e)
 {
     if (event_key == btnPoint)  {   //decimal point click
            
        if (equal == true || 
             num1 == Convert.ToDouble(InputBox.Text))  {
                    InputBox.Text = ".";
        }
        else if (InputBox.Text.Contains('.')) {
           return;
        }
        else {
            setValues(".");
        }
     }
     else if (event_key == btn0) { // 0 button clicked
        setValues("0"); }    
     else if (event_key == btn1) {    // 1 button clicked
        setValues("1"); } 
     else if (event_key == btn2) {    // 2 button clicked
        setValues("2"); }
     else if (event_key == btn3) {    // 3 button clicked
        setValues("3"); } 
     else if (event_key == btn4) {    // 4 button clicked
        setValues("4"); }
     else if (event_key == btn5) {   // 5 button clicked
        setValues("5"); } 
     else if (event_key == btn6) {   // 6 button clicked
        setValues("6"); }
     else if (event_key == btn7) {   // 7 button clicked
        setValues("7"); }  
     else if (event_key == btn8) {   // 8 button clicked
        setValues("8"); } 
     else if (event_key == btn9) {   // 9 button clicked
         setValues("9"); }
  }

/******************************************************
         *  onKeyDown() checks keypad events
*******************************************************/
   private void onKeyDown(object event_key, KeyEventArgs e)
   {

   }
/******************************************************
         * Clear() method
*******************************************************/
   private void Clear() {

   }

    
/*****************************************************
         * setValues() method
******************************************************/
        private void setValues(string str)
        {

        }
/*************************************************************
 * getSolution() method is called to handle the arimetic 
 * operations.
 *  The logic is:
 * 1- If num1 == 0 then set num2 to num1
 * 2- Use a switch construct to determine which math operation
      to perform
 *    a- Addition
 *    b- Subtraction
 *    c- Multiplcation
 *    d- Division
 * 3- Convert result to string and store it in input box.
 *
 *********************************************************/
        private void getSolution()
        {

        }
                       
 /***************************************************************
 * btnSQRT() method is the event handler calculating squre roots.
****************************************************************/
        private void btnSQRT_Click(object event_key, EventArgs e)
        {

        }

/*******************************************************************
 * Basic_Calc() method is the event handler on Basic_Calc being 
 * loaded.
 *******************************************************************/
        private void Calculator_Load(object event_key, EventArgs e)
        {

        }

/*****************************************************************
 * bCopy_Click() method is the event handler for the Copy button
 *  being clicked. It causes the application to copy the contents 
 * of the InputBox.
 *****************************************************************/
        private void bCopy_Click(object event_key, EventArgs e)
        {
            
        } 

/******************************************************************
 * btnOFF_Click() method is the event handler for the OFF 
 * clicked. It causes the application to exit. 
 *****************************************************************/
        private void btnOFF_Click(object event_key, EventArgs e)
        {
           Application.Exit();
        } 

/*****************************************************************
 * btnabout_Click() method is the event handler for the About 
 * button being clicked. It displays a sumtotalz.com Home page in 
 * Internet Explorer.     
 *****************************************************************/
        private void btnabout_Click(object event_key, EventArgs e)
        {

        } 

  /***********************************************************
   * btnHelp_Click() method is the event handler for the Help 
   * button beingclicked. It displays a help page in Internet 
   * Explorer.
   **********************************************************/
        private void btnHelp_Click(object event_key, EventArgs e)
        {

        } 
    }
}

  
Figure 6: Basic_Calc.cs - Event Handler

How Do We Get Started?

We will use C#: Introduction to Forms as a tutorial on how to get started. Figure 1 consists of twenty-two push buttons and an edit box. Twenty of these buttons allow us to enter and operate on the data. In addition, Figure 1 contains an About and a Help button. We will use the above templates outlined in Figures 1 through 4.

  • We are using the MS Visual Studio IDE to develop our calculator.
  • We got started via C#: Introduction to Forms.
  • Add the buttons and text box by clicking on the Toolbox tab on the right side of the IDE.
  • Next we will use Figure 4 as a template to define our Calculator namespace in file Basic_Calc.Designer.cs. We must have an event handler for each button. These event handlers will be defined as methods.
  • The data we will be working with is entered in the edit box. We must know what data is entered and a way to capture this data. Once we have the data, one or two numbers, we must have captured the operation the user wants to perform. The digits that comprise the numbers and the operations cause events to be registered when the user presses the following buttons:
In the next section, we will show how we tell MS which method is associated with which button.

Event Handlers

What are event handlers? Event handlers are methods/code that MS calls in response to an event such as the pressing/clicking of a button. MS uses the resource Id/buttonname to associate a button with the event handling code. Consider the following code snippet:

 
else if (event_key == btn0) { // 0 button clicked
   setValues("0"); }     
else if (event_key == btn1) {  // 1 button clicked
   setValues("1"); }    
else if (event_key == btn2) { // 2 button clicked
   setValues("2"); }     
else if (event_key == btn3) { // 3 button clicked
   setValues("3"); }     
else if (event_key == btn4) { // 4 button clicked
   setValues("4"); }  
else if (event_key == btn5) {  // 5 button clicked
   setValues("5"); }    
else if (event_key == btn6) { // 6 button clicked
   setValues("6"); }     
else if (event_key == btn7) { // 7 button clicked
   setValues("7"); }     
else if (event_key == btn8) {  // 8 button clicked
   setValues("8"); }    
else if (event_key == btn9) { // 9 button clicked
   setValues("9"); }     
            //
else if (event_key == btnPlus) { 
     getSolution();  oper = '+'; }  //Plus button clicked
else if (event_key == btnMinus) { 
      getSolution();  oper = '-'; } //Minus button clicked
else if (event_key == btnMultiply) { 
      getSolution();  oper = '*'; } //Multiply button clicked
else if (event_key == btnDivide) { 
      getSolution();  oper = '/'; } //Division button clicked
else if (event_key == btnEqual) { 
      getSolution();

Clear();        //Equal button clicked

/********************************************************
 * btnOFF_Click() method is the event handler for the OFF 
 * button being clicked. It causes the application to exit.
 *********************************************************/
  private void btnOFF_Click(object event_key, EventArgs e)
  {
     Application.Exit();
  } 

 
Figure 7: Event handling snippet

In figure 5, btnOFF is the resource ID/button name. This is how MS identifies a particular resource. We can the associate the resource Id with a method as shown in the following example.

In Figure 5, the following occurs:
  1. btnOFF - identifies the OFF push button
  2. btnOFF_Click - is identified as the event handler for the OFF push button, using the btnOFF button name
btnOFF allows MS to associate the OFF push button with the btnOFF_Click event handler. This association is resolved at compiled time. The compiler resolving the push button resource with a method is similar to the compiler resolving an int a declaration with its proper attributes. We used this knowledge to assign event handlers to the resources causing the events in Figure 5: Event handling snippet.

Conclusions

In this tutorial, we have learned how to build a five function calculator application. The functions that are included in this application are:

  • Addition - adds two numbers: n1 + n2;
  • Subtraction - subtracts number two from number one: n1 - n2;
  • Multiplication - Multiplies two numbers: n1 * n2;
  • Division - divides number two into number one: n1 / n2;
  • =/- - toggles the sign of the number in the entry box.
We used a Building the MS Visual Studio Basic Application Template and Holland's OOP Programming Design Model to build this application.

Definitions

Comment - comments help document a program but do cause the computer to perform any action. They are ignored when the program executes. They are of the form:

  • // this symbol indicates that all that follows the // is a comment
  • A multiline comment starts with /* and ends with */
    /*
     * This is a multiline comment
     */
    

Function - a named section of a program that performs the specific task included between the { and the }.

persistent data - is data that exists after the exit of an application or the turning off of the computer. It exists on a media storage device (e.g., hard disk).

CStatic

    The CStatic class provides the functionality of a Windows static control. A static control is a control used to display text, to draw frames or lines separating other controls, or to display icons. A static control doesn't accept user input, but it can notify its parent of stylus taps if it's created with SS_NOTIFY style.

Form - The Form class encapsulates the functionality of a Windows form.

Graphical user interface (GUI) - allows users to interact with electronic devices through graphical icons (e.g., push buttons).

MS Visual Studio IDE

    The Visual Studio Integrated Development Environment (IDE) offers a set of tools that help you write and modify the code for your programs, and also detect and correct errors in your programs.

System -

    The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.




HOME] Consulting Design Maintenance Project Testing Training Turnkey Java c# SQL HTML JavaScript c#

2002 - 2013 All Rights Reserved Total Application Works