Skip to content

Instantly share code, notes, and snippets.

@ChlorUpload
Last active September 7, 2019 17:05
Show Gist options
  • Save ChlorUpload/ae2f9f1faaa18d93ae5414b92e1d1296 to your computer and use it in GitHub Desktop.
Save ChlorUpload/ae2f9f1faaa18d93ae5414b92e1d1296 to your computer and use it in GitHub Desktop.
A calculator recognizing addition and multiplication
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX 128
bool is_digit(char ch) { return (ch >= '0' && ch <= '9'); }
int main(void)
{
bool mul = false;
int number[MAX], cnt = 0;
char expression[MAX];
scanf_s("%s", expression, MAX);
int i, sum = 0;
for (i = 0; i <= strlen(expression); i++)
{
if (is_digit(expression[i]))
{
sum *= 10;
sum += (int)(expression[i] - '0');
}
else
{
if (mul)
{
number[cnt - 1] *= sum;
sum = 0;
mul = false;
}
else
{
number[cnt] = sum;
cnt++;
sum = 0;
}
if (expression[i] == '*')
{
mul = true;
}
}
}
for (i = 0; i < cnt; i++)
{
printf("\n%d", number[i]);
sum += number[i];
}
printf("\n%d", sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment