luc098.c ​
Metadata ​
- Author — Amit Dutta
- Last updated — 08 Feb 2026
- License — MIT License (See the LICENSE file for details)
Problem Statement ​
Problem Statement
Write a calculator utility using command line arguments.\nUsage: calc <switch> <n> <m>\nwhere switch is arithmetic operator or comparison operator.
Source Code ​
Printing the code
To print this file, open it on GitHub and click Raw before printing, or use the Download Raw button above and print directly from that page.
c
#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;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64