Skip to content

luc098.c

Problem Statement

Write a calculator utility using command line arguments.\nUsage: calc \nwhere switch is arithmetic operator or comparison operator.

Metadata

Property Detail
Author Amit Dutta amitdutta4255@gmail.com
Date 08 Feb 2026
License MIT License (See the LICENSE file for details)

Actions

Raw View on GitHub

💡 You can print or save this file by opening Raw and using your browser.

Source Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    float n, m, res;
    char operator;

    if (argc != 4)
    {
        printf("Usage: %s <switch> <n> <m>\n", argv[0]);
        printf("Example: %s + 10 20\n", argv[0]);
        printf("Note: For multiplication (*), use '*' or x to avoid shell expansion.\n");
        exit(1);
    }

    operator = argv[1][0]; // First character of the switch argument
    n = atof(argv[2]);
    m = atof(argv[3]);

    switch (operator)
    {
    // Arithmetic
    case '+':
        printf("%.2f\n", n + m);
        break;
    case '-':
        printf("%.2f\n", n - m);
        break;
    case 'x': 
    case '*':
        printf("%.2f\n", n * m);
        break;
    case '/':
        if (m == 0) printf("Error: Division by zero\n");
        else printf("%.2f\n", n / m);
        break;
    case '%':
        printf("%d\n", (int)n % (int)m);
        break;

    // Comparison
    case '<':
        printf("%s\n", (n < m) ? "True" : "False");
        break;
    case '>':
        printf("%s\n", (n > m) ? "True" : "False");
        break;

    // Handling symbols that might be multi-char (e.g. <=, >=, ==) is tricky 
    // with argv[1][0], but basic logic for typical single char switches:
    case '=':
        printf("%s\n", (n == m) ? "True" : "False");
        break;

    default:
        printf("Unknown operator: %c\n", operator);
        break;
    }

    return 0;
}