Skip to content

Instantly share code, notes, and snippets.

@chengluyu
Created May 7, 2017 16:56
Show Gist options
  • Save chengluyu/9714b8662ddc4f3a797b8eae655ce1cc to your computer and use it in GitHub Desktop.
Save chengluyu/9714b8662ddc4f3a797b8eae655ce1cc to your computer and use it in GitHub Desktop.
LL(1) Calculator Written in C
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define BUFFER_SIZE 256
int value();
int integer();
int factor();
int term();
const char *expr = NULL;
int at = 0;
int main() {
puts("Please enter an arithmetic expression:");
char buf[BUFFER_SIZE];
memset(buf, BUFFER_SIZE, 0);
gets(buf);
expr = buf;
printf("The result is %d.\n", factor());
return 0;
}
int value() {
if (expr[at] == '(') {
at++;
int v = factor();
if (expr[at] == ')') {
at++;
return v;
} else {
printf("Expected a bracket at %d instead of %c.\n", at, expr[at]);
exit(1);
}
} else {
return integer();
}
}
int integer() {
int v = 0;
int negative = expr[at] == '-';
if (negative) {
at++;
}
if (isdigit(expr[at])) {
do {
v *= 10;
v += expr[at++] - '0';
} while(isdigit(expr[at]));
} else {
printf("Expected a integer at position %d.\n", at);
exit(1);
}
return negative ? -v : v;
}
int factor() {
int v = term();
while (expr[at] == '+' || expr[at] == '-') {
if (expr[at++] == '+') {
v += term();
} else {
v -= term();
}
}
return v;
}
int term() {
int v = value();
while (expr[at] == '*' || expr[at] == '/') {
if (expr[at++] == '*') {
v *= value();
} else {
v /= value();
}
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment