C examples for Statement:switch
Create an interactive calculator.
#include <stdio.h> #include <stdbool.h> int main(void) { double accumulator = 0.0; double number; char operator1; bool isCalculating = true; while (isCalculating) { scanf("%lf %c", &number, &operator1); switch (operator1) { case '+': accumulator += number;//from www. ja v a2s. c o m break; case '-': accumulator -= number; break; case '*': accumulator *= number; break; case '/': if (number == 0) printf("ERROR: Division by 0 is not allowed!"); else accumulator /= number; break; case 'S': accumulator = number; break; case 'E': isCalculating = false; break; default: printf("ERROR: Unknown operator!\n"); break; } printf("= %f\n", accumulator); } return 0; }