C++: Learning the Basics – Programming a simple calculator

Situation: User types in an expression (e.g. 5+9) and the program gives the answer (14).

Code:

#include <iostream.h>
#include <conio.h>
void main()
{
     clrscr();
     int num1, num2, ans;
     char action;

     do
     {
           cout<<"\n\t Enter a number: ";
           cin>>num1;

           cout<<"\n\t Enter an action: ";
           cin>>action;

           cout<<"\n\t Enter another number: ";
           cin>>num2;

           if (action=='+')
           { 
                ans=num1+num2;
           }
           else if (action=='-')
           {
                ans=num1-num2;
           }
           else if (action=='*')
           {
                ans=num1*num2;
           }
           else if (action=='/')
           {
                ans=num1/num2;
           }
           else 
           {
               cout<<"\n\t Error in action! Choose +, -, * or /."
           }
           cout<<"\n\t The answer is "<<ans;

           cout<<"\n\t Do you want to continue? Y or N?";
           cin>>char2;
           
     }while (char2=='Y');
     getch;
     }



Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s