Sunday, December 9, 2012

Program Pascal STACK

program infix_postfix;
uses crt;
type s100 = string[100];
stacks = record
stack : s100;
top : 0..100
end;
var infix, postfix : s100;
operator : set of char ;
x,y:byte;
i:integer;

procedure push (var s : stacks; elements : char);
begin
s.top := s.top + 1;
s.stack[s.top] := elements
end;

function pop (var s : stacks) : char;
begin
pop := s.stack[s.top];
s.top := s.top - 1;
end;

function priority (tanda : char) : integer;
begin
case tanda of
'^' : priority := 3;
'*', '/' : priority := 2;
'+', '-' : priority := 1;
'(' : priority := 0
end
end;

procedure convert (infix : s100);
var i : integer;
test : boolean;
temp, kar : char;
s : stacks;
begin
postfix:='';
for i := 1 to length(infix) do
    begin
    kar := infix[i];
    if kar = '(' then push(s, kar)
    else if kar = ')' then
        begin
        while s.stack[s.top] <> '(' do
        postfix:=postfix + pop(s);
        temp := pop(s)
        end
    else if kar in operator then
        begin
        while (s.top <> 0) and (priority(kar) <= priority(s.stack[s.top])) do
        postfix:=postfix + pop(s);
        push(s, kar)
        end
    else if kar <> ' ' then postfix:=postfix + kar;
    end;
    if s.top <> 0 then
        repeat
        postfix:=postfix + pop(s)
        until s.top = 0;
end;

procedure animate(postfix:string);
begin
x:=13;
    for i:=1 to length(postfix) do
        begin
        for y:=7 to 14 do
            begin
            gotoxy(x,y);write(postfix[i]);
            gotoxy(x,y-1);write(' ');
            delay(20);
            end;
    x:=x+1;
    delay(50);
    end;
end;

begin
clrscr;
operator:= ['^','*','/','+','-'];
writeln('===================================');
writeln('|  mengubah infix menjadi postfix  |');
writeln('===================================');
gotoxy (5,7);
write('infix = ');
readln(infix);
gotoxy (5,14) ;
write('hasil = ');
convert (infix);
animate(postfix);
gotoxy(13,7); write(infix);
gotoxy (5,16);
writeln('terimakasih atas partisipasi anda');
readln;
end.



No comments:

Post a Comment