I just wanted to give an example of a simple and easy C++ program you can write. This program takes two integers and adds them, subtracts them, multiplies them, divides them, finds the remainder of them after division, or computes powers of them. Feel free to use this program however you want.
#include
using namespace std;
int cal(int a, int b, char c)
{
switch(c)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
case '%':
return a % b;
case '^':
int temp = a;
for(int x = 1; x < b; x++)
a *= temp;
return a;
}
}
int main()
{
cout << "Welcome to Calculator!\n"
<< "Enter one operation at a time.\n"
<< "Supported operators: + - * / ^ %\n"
<< "Format: integer operator integer\n\n";
int a, b;
char c;
while(1)
{
cout << ">";
cin >> a >> c >> b;
if(!(c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^') )
{
cout << "Invalid operator.\n";
continue;
}
cout << "= " << cal(a,b,c) << endl;
end:;
cout << "Continue? y for yes, any other key for no: ";
cin >> c;
if(c != 'y')
break;
}
cout << "Goodbye!\n";
return 0;
}
main()
- prints welcome statement
- int a <-- stores first number
- int b <-- stores second number
- char c <-- stores operator
- while(1) <-- this will loop forever (until the program hits a break statement)
- prints the prompt
- scans for a, b, and c
- if the operator was not one of the 6 supported, print "Invalid operator" and end the current loop iteration
- print "= " and call the cal() function to compute the answer
- ask if the user wants to continue
- if the user doesn't input 'y' exit the while loop
- print "Goodbye!"
cal()
- this function calculates the answer
- variables a, b, and c serve the same purpose
- each case of the switch statement is self-explanatory except the last one
- case: '^'
- temp <-- to hold the value of a
- multiply a by temp b times
- return the answer
And finally, here is some sample output:
[cmw4026@omega test]$ ./a.out
Welcome to Calculator!
Enter one operation at a time.
Supported operators: + - * / ^ %
Format: integer operator integer
>5 + 5
= 10
Continue? y for yes, any other key for no: y
>5 - 10
= -5
Continue? y for yes, any other key for no: y
>6 * 12
= 72
Continue? y for yes, any other key for no: y
>18 / 3
= 6
Continue? y for yes, any other key for no: y
>10 % 3
= 1
Continue? y for yes, any other key for no: y
>2 ^ 4
= 16
Continue? y for yes, any other key for no: n
Goodbye!
[cmw4026@omega test]$