Click here to Skip to main content
15,889,808 members
Articles / Programming Languages / C#
Tip/Trick

A Simple Calculator in Windows Forms

Rate me:
Please Sign up or sign in to vote.
4.86/5 (6 votes)
14 Dec 2014CPOL1 min read 129.2K   6.3K   10   4
A demonstation of accumulators and operators

Introduction

I created this application in response to this question about how to implement a simple calculator.

Using the Code

C#
using System;
using System.Windows.Forms;

namespace RedCell.App.Calculator.Example
{
    public partial class Form1 : Form
    {
        private double accumulator = 0;
        private char lastOperation;

        public Form1()
        {
            InitializeComponent();
        }

        private void Operator_Pressed(object sender, EventArgs e)
        {
            // An operator was pressed; perform the last operation and store the new operator.
            char operation = (sender as Button).Text[0];
            if (operation == 'C')
            {
                accumulator = 0;
            }
            else
            {
                double currentValue = double.Parse(Display.Text);
                switch (lastOperation)
                {
                    case '+': accumulator += currentValue; break;
                    case '-': accumulator -= currentValue; break;
                    case '×': accumulator *= currentValue; break;
                    case '÷': accumulator /= currentValue; break;
                    default: accumulator = currentValue; break;
                }
            }

            lastOperation = operation;
            Display.Text = operation == '=' ? accumulator.ToString() : "0";
        }

        private void Number_Pressed(object sender, EventArgs e)
        {
            // Add it to the display.
            string number = (sender as Button).Text;
            Display.Text = Display.Text == "0" ? number : Display.Text + number;
        }
    }
}

The way it works is simple.

  1. There are two kinds of buttons, numbers and operators.
  2. There is a display that shows entries and results.
  3. There is an accumulator variable to store the accumulated value.
  4. There is a lastOperation variable to store the last operator, because we won't evaluate until another operator is pressed.

When a number is pressed, it is added to the end of the number currently on the display. If a 0 was on the display we replace it, just to look nicer.

If the C operator is pressed, we reset the accumulator to 0.

Otherwise we perform the last operation against the accumulator and the currently entered number. If there wasn't a lastOperation, then we must be starting a new calculation, so we set the accumulator to the currentValue as the first operation.

Points of Interest

Trying to emulate a basic calculator can be a good exercise for a new programmer. I created this application in 15 minutes to demonstrate that it does not need to be complicated.

C# is somewhat verbose. What could you do to use less code? Calculators these days are pretty smart, but back in the olden days when I started programming for embedded systems it would be common to only have 100 bytes or less of memory in which the program was stored, so writing the code (in machine language) to be as small as possible was important.

Back to work...

History

  • December 14, 2014 - Wrote this

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer Robotic Assistance Devices / AITX
Canada Canada
Yvan Rodrigues has 30 years of experience in information systems and software development for the industry. He is Senior Concept Designer at Robotic Assistance Devices

He is a Certified Technician (C.Tech.), a professional designation granted by the Institute of Engineering Technology of Ontario (IETO).

Yvan draws on experience as owner of Red Cell Innovation Inc., Mabel's Labels Inc. as Manager of Systems and Development, the University of Waterloo as Information Systems Manager, and OTTO Motors as Senior Systems Engineer and Senior Concept Designer.

Yvan is currently focused on design of embedded systems.

Comments and Discussions

 
QuestionNeed an explanation for the above code snippet Pin
Sachin Vakuund11-Apr-17 0:33
Sachin Vakuund11-Apr-17 0:33 
Questionquestion about -2-5 dont work Pin
Tuan Nguyen8-Feb-17 4:59
Tuan Nguyen8-Feb-17 4:59 
QuestionNo Doubt Pin
Member 1059489016-Dec-14 1:18
Member 1059489016-Dec-14 1:18 
AnswerRe: No Doubt Pin
Yvan Rodrigues16-Dec-14 4:26
professionalYvan Rodrigues16-Dec-14 4:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.