Simple calculator program in c++ using functions | Switch-case program in C++ | Ask The Code
Problem:
Write a simple calculator program in C++ using functions, which will perform basic computations.
You also ensures that the program should allow us to compute values as much time as we want, i.e., your program should be using do - while loop. And if wanted, then you can use the switch - case as well.
Code:
#include<bits/stdc++.h>
using namespace std;
#define num long long int
void mod(){
num a,b;
cout << "Enter the values: ";
cin >> a >> b;
cout << a%b << endl;
}
void sqr(){
num a;
cout << "Enter the value: ";
cin >> a;
cout << a*a << endl;
}
void cube(){
num a;
cout << "Enter the value: ";
cin >> a;
cout << a*a*a << endl;
}
void add(){
num a,b;
cout << "Enter the values: ";
cin >> a >> b;
cout << a+b << endl;
}
void sub(){
num a,b;
cout << "Enter the values: ";
cin >> a >> b;
cout << a-b << endl;
}
void mult(){
num a,b;
cout << "Enter the values: ";
cin >> a >> b;
cout << a*b << endl;
}
void div(){
num a,b;
cout << "Enter the values: ";
cin >> a >> b;
cout << a/b << endl;
}
int main(){
cout << "\t\t\tA Simple Calculator Program\n\n" << endl;
int choice;
do{
int oper;
cout << "Choose the operation you want to perform: " << endl;
cout << "1 to add\t2 to subtract\t3 to multiply\t4 to divide" << endl;
cout << "5 to mod\t6 to square\t7 to cube." << endl;
cout << "or enter any other value to exit the program: ";
cin >> oper;
switch(oper){
case 1:
add();
break;
case 2:
sub();
break;
case 3:
mult();
break;
case 4:
div();
break;
case 5:
mod();
break;
case 6:
sqr();
break;
case 7:
cube();
break;
default:
cout << "Wrong Selection!" << endl;
}
cout << "Want to do another computation ? Press 1: " << endl;
cin >> choice;
}while(choice == 1);
cout << "Exited the program successfully." << endl;
return 0;
}
Sample Output of the above program:
A Simple Calculator Program
Choose the operation you want to perform:
1 to add 2 to subtract 3 to multiply 4 to divide
5 to mod 6 to square 7 to cube.
or enter any other value to exit the program: 1
Enter the values: 20 2
22
Want to do another computation ? Press 1:
1
Choose the operation you want to perform:
1 to add 2 to subtract 3 to multiply 4 to divide
5 to mod 6 to square 7 to cube.
or enter any other value to exit the program: 7
Enter the value: 72
373248
Want to do another computation ? Press 1:
1
Choose the operation you want to perform:
1 to add 2 to subtract 3 to multiply 4 to divide
5 to mod 6 to square 7 to cube.
or enter any other value to exit the program: 3
Enter the values: 12345 123
1518435
Want to do another computation ? Press 1:
2
Exited the program successfully.
Comments