You are on page 1of 5

Prvi zadatak

Lekser

%{

#include "times.tab.h"

%}

%%

[ \t]+ ;

[0-9]+ { yylval.integer = atoi(yytext); return INTCONST; }

"*" { return ASTERISK; }

"+" { return PLUS; }

"-" { return MINUS; }

"(" { return OPEN_ PARENTHESES; }

")" { return CLOSE_ PARENTHESES; }

%%

int yywrap(void) { return 1; }

Parser

%{

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

typedef struct node_str {

int elem;

struct node_str* left;

struct node_str* right;

}* Node;

Node ast = NULL;


int evaluate(Node l);

%}

%union {

int integer;

struct node_str* node_ptr;

%token PLUS

%token MINUS

%token ASTERISK

%token OPEN_PARENTHESES

%token CLOSE_PARENTHESES

%token <integer> INTCONST

%type <node_ptr> e

%left PLUS

%left MINUS

%left ASTERISK

%%

e : e PLUS e

$$ = (Node)malloc(sizeof(struct node_str));

$$->elem = '+';

$$->left = $1;

$$->right = $3;

ast = $$;

| e MINUS e

{
$$ = (Node)malloc(sizeof(struct node_str));

$$->elem = '-';

$$->left = $1;

$$->right = $3;

ast = $$;

| e ASTERISK e

$$ = (Node)malloc(sizeof(struct node_str));

$$->elem = '*';

$$->left = $1;

$$->right = $3;

ast = $$;

| OPEN_ PARENTHESES e CLOSE_ PARENTHESES

$$ = $2;

| INTCONST

$$ = (Node)malloc(sizeof(struct node_str));

$$->elem = $1;

$$->left = NULL;

$$->right = NULL;

ast = $$;

};

%%

yyerror(const char *s) {

fprintf( stderr, "%s\n", s );


}

void main() {

yyparse();

printf("%d\n", evaluate(ast));

int evaluate(Node l) {

if( l == NULL )

return 0;

if( l->left == NULL && l->right == NULL )

return l->elem;

if( l->elem == '+' )

return evaluate(l->left) + evaluate(l->right);

if( l->elem == '-' )

return evaluate(l->left) - evaluate(l->right);

if( l->elem == '*' )

return evaluate(l->left) * evaluate(l->right);

}
Drugi zadatak

Kod:

counter=0; result=2;

while (counter < 20)

result = (result * counter ) - counter;

if(result < 100)

print result;

end;

counter++;

end

Program množi i oduzima isti broj, koji se postepeno povećava, od ukupnog rezultata. Dok god je
rezultat manji od 100 on se ispisuje za svako izvođenje petlje.

You might also like