Get three inputs in the format: integer, character, integer. The inputs are all separated by spaces. Perform the operation with the integer values based on the character (+
, -
, *
, /
). Display the calculated value as the output.
Example: 23 + 45 o/p : 68
Operator | Operation | Example |
---|---|---|
+ | Addition | 17 + 15 = 32 |
- | Subtraction | 20 - 8 = 12 |
* | Multiplication | 5 * 6 = 30 |
/ | Division (Integer) | 11 / 7 = 1 |
% | Modulo (Remainder) | 11 % 7 = 4 |
Accept an Integer, Character, Integer as input (space-separated)
Print the output as integer
-10^9 <= INPUT <= 10^9
#include <iostream> using namespace std; int main() { long long a, b, ans; char ch; cin >> a >> ch >> b; if (ch == '/') ans = a / b; else if (ch == '+') ans = a + b; else if (ch == '-') ans = a - b; else if (ch == '*') ans = a * b; else if (ch == '%') ans = a % b; cout << ans; return 0; }
==
to compare characters for operator detection%
operator'+'
(single quotes) for characters, not "+"
(double quotes for strings)ans
should be assigned in all cases, or use else
for invalid operatorb == 0
when dividing - could cause runtime errorint
instead of long long
may cause overflow for large numbersThis problem is perfect for demonstrating switch
statement, which is cleaner for character-based decisions:
switch (ch) { case '+': ans = a + b; break; case '-': ans = a - b; break; case '*': ans = a * b; break; case '/': ans = a / b; break; case '%': ans = a % b; break; default: cout << "Invalid operator"; }
break
statements prevent fall-through to next caseif (b == 0 && (ch == '/' || ch == '%'))
double
for decimal division results