Sir, I have been unable to solve the basic calculator challenge for quite some time. Despite viewing the editorial. Kindly tell me the logic/ solution.
Basic Calculator Challenge
Hello @aan,
You can follow the following approach:
-
Take the first input as ch
char ch;
cin>>ch; -
use a while loop which will iterate for each input till the input is not βXβ or βxβ:
while(ch!=βXβ || ch!=βxβ){} -
Inside the use if else conditional statements:
3.1. if ch == β+β:
β¦Take two more inputs n1 and n2 (as integers)
β¦and print the addition of both as ouput
3.2. repeat the same for β-β, β*β, β/β, and β%β
3.3. for any other input you can use else statement:
β¦Print βInvalid operation. Try again.β inside that
Share your code, if you would stuck or face any issue.
Hope, this would help.
Give a like, if you are satisfied.
How do I fix this?
i know that i should put the ch in a loop but I am unable figure out. Kindly help me out. Thanksβ¦
#include
using namespace std;
int main() {
char ch;
cin>>ch;
while(ch!=βXβ|| ch!=βxβ){
if (ch==β+β){
int n1,n2;
cin>>n1>>n2;
cout<<n1+n2;
}
if (ch==β-β){
int n1,n2;
cin>>n1>>n2;
cout<<n1-n2;
}
if (ch==ββ){
int n1,n2;
cin>>n1>>n2;
cout<<n1n2;
}
if (ch==β/β){
int n1,n2;
cin>>n1>>n2;
cout<<n1/n2;
}
if (ch==β%β){
int n1,n2;
cin>>n1>>n2;
cout<<n1%n2;
} else{
cout<<βinvalid operation. try again.β;
}
}
return 0;
}
From next time, share your code using Online Coding Blocks IDE.
The way you have send it, is introducing many syntax errors in it.
Steps:
- Paste your code on IDE.
- Save it there.
- Share the URL generated.
Now, coming back to your code:
Solution of what you have asked is,
add the following code as the last statement inside the while loop:
while(){
β¦
β¦
β¦
//last statement:
cin>>ch;
}
The loop would iterate again if ch is neither βXβ nor βxβ.
Hope, this would help.
Give a like, if you are satisfied.
I hope Iβve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.