Basic Calculator Challenge

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.

Hello @aan,

You can follow the following approach:

  1. Take the first input as ch
    char ch;
    cin>>ch;

  2. use a while loop which will iterate for each input till the input is not β€˜X’ or β€˜x’:
    while(ch!=β€˜X’ || ch!=β€˜x’){}

  3. 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.

1 Like

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<<n1
n2;
}
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:

  1. Paste your code on IDE.
  2. Save it there.
  3. 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.

1 Like

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.