a simple 4 function calculator : Switch « Language Basics « C / ANSI-C






a simple 4 function calculator

#include <stdio.h>
int main()
{
    char  line[100];
    int   result =0;
    char  operator;
    int   value;

    while (1) {
        printf("Result: %d\n", result);
        printf("Enter operator and number: ");

        fgets(line, sizeof(line), stdin);
        sscanf(line, "%c %d", &operator, &value);

        if ((operator == 'q') || (operator == 'Q'))
            break;
        switch (operator) {
        case '+':
            result += value;
            break;
        case '-':
            result -= value;
            break;
        case '*':
            result *= value;
            break;
        case '/':
            if (value == 0) {
                printf("Error:Divide by zero\n");
                printf("   operation ignored\n");
            } else
                result /= value;
            break;
        default:
            printf("Unknown operator %c\n", operator);
            break;
        }
    }
    return (0);
}


           
       








Related examples in the same category

1.Switch demo
2.How to use switch: number
3.How to use switch: char
4.Switch: char and nested if
5.Switch inside for loop
6.Switch with int case
7.Switch with char case
8.Get three input at the same time: scanf
9.Console menu: switch with char case
10.Switch with default