WHAT'S NEW?
Loading...

Building a simple calculator in C++




Ever though how programmers code huge software's and want to be one of them. No one became a expert programmer from birth, they practice and code everyday and you could be one by doing the same. There are some building block of programming and understanding the concept is most important. Here's a tutorial and I'm gonna show you how to build a basic calculator in C++  in minutes. The following code was written in code block IDE and works perfectly till date. So let's get started.

I've divided the code in various segments and i'll be describing those in steps. The segments are : 
  • Basic C++ skeleton
  • grabbing the values from user
  • processing
  • output
1. Basic C++ skeleton

The basic C++ skeleton is the raw code used in every C++ program. Here's the skeleton.



Here, #include<iostream.h> is for adding the iostream header file which contains information for various syntax like cout, cin. Basically our program wont work if the line isn't included. main() is the main part of our program. Every piece of other information goes  into main(). 
Note : If #include<iostream.h> shows some king of error, try removing .h
2. Grabbing the values from the user


In his part we get values form the user. First we display a simple a simple text saying "Calculator". Next we  initialize the variables. We have three float variables and a char variable. Two float's are used for getting a values of two numbers from the user and third float is used for the result. A single char is used for storing the operation. 

Next we ask the user to input their first number then second number and then the operation. 

After the operation, our code should look something like this.




3. Processing

Now we are in brain of our code, the processing. Here it's decided what would be the final answer. We use IF/ Else If and Else operators for this function. If the user enter a + our result is num1+num2, if entered a - result is num1- num2, if entered a * or x the answer is num1 * num2 and finally if entered a / our result is num1 / num2. If the user enters something different than the given operators, a text is shown saying wrong operator.

After implementing the following in our code, it should look something like this : 



4. Output

When done with the most important part, we add one simple line to the code i.e. outputting the answer and our final code should look something like this : 





So, that was quite simple, I guess. If you had any problems in understanding the concept behind how a calculator is made. Here's a tutorial video on doing this. I believe watching a video is simpler than reading the whole post.




  


0 comments:

Post a Comment