Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- typedef struct node
- {
- char el;
- struct node *left, *right;
- } node;
- node* create_node(char c)
- {
- node *my = malloc(sizeof(*my));
- my->el = c;
- my->left = NULL;
- my->right = NULL;
- return my;
- }
- bool is_digit(char c)
- {
- return (c >= '0' && c <= '9');
- }
- void error(int code)
- {
- if (code == 0)
- printf("UNMATCHED BRACKETS\n");
- if (code == 1)
- printf("INCORRECT EXPRESSION\n");
- if (code == 2)
- printf("INCORRECT SYMBOL\n");
- exit(0);
- }
- char op;
- node* expression(void);
- node* summand(void);
- node* multi(void);
- node* build_tree(void)
- {
- scanf("%c", &op);
- node *root = expression();
- if (op == '(' || op == ')')
- error(0);
- if (op == '*' || op == '+' || op == '-' || op == 'x' || op == 'X' || is_digit(op))
- error(2);
- if (op != '.')
- error(1);
- return root;
- }
- void print_tree(node *cur)
- {
- if (cur == NULL)
- return;
- print_tree(cur->left);
- printf("%c", cur->el);
- print_tree(cur->right);
- }
- int calc_expression(node *cur, int x)
- {
- if (cur == NULL)
- return 0;
- if (cur->left == NULL && cur->right == NULL)
- {
- if (cur->el == 'x' || cur->el == 'X')
- return x;
- return cur->el - '0';
- }
- int op1 = calc_expression(cur->left, x);
- int op2 = calc_expression(cur->right, x);
- if (cur->el == '+')
- return op1 + op2;
- if (cur->el == '-')
- return op1 - op2;
- return op1 * op2; //if cur->el == '*'
- }
- node* expression(void)
- {
- node* left = summand();
- while (op == '+' || op == '-')
- {
- node *cur = create_node(op);
- scanf("%c", &op);
- node *right = summand();
- cur->left = left;
- cur->right = right;
- left = cur;
- }
- return left;
- }
- node* summand(void)
- {
- node* left = multi();
- while (op == '*')
- {
- node *cur = create_node(op);
- scanf("%c", &op);
- node *right = multi();
- cur->left = left;
- cur->right = right;
- left = cur;
- }
- return left;
- }
- node* multi(void)
- {
- if (is_digit(op) || op == 'x' || op == 'X')
- {
- node *cur = create_node(op);
- scanf("%c", &op);
- return cur;
- }
- if (op == '(')
- {
- scanf("%c", &op);
- node *cur = expression();
- if (op != ')')
- error(0);
- scanf("%c", &op);
- return cur;
- }
- if (op == ')')
- error(0); //unmatched brackets
- if (op == '.' || op == '+' || op == '-' || op == '*')
- error(1); //incorrect expresion
- error(2); //incorrect symbol in expression
- return NULL;
- }
- int main(void)
- {
- printf("ENTER ARITHMETIC EXPRESSION WITH VARIABLE X\n");
- printf("EXPRESSION MUST CONSIST ONLY OF '*', '+', '-', digits, '(', ')' AND VARIABLES 'x' (or 'X'):\n");
- node *root = build_tree();
- printf("ENTER THE VALUE OF VARIABLE 'x' ('X'):\n");
- int x;
- scanf("%d", &x);
- //print_tree(root);
- int ans = calc_expression(root, x);
- printf("THE VALUE OF EXPRESSION AT POINT X IS %d", ans);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement