How to implement a stack using an array in Pascal

1 Answer

0 votes
program StaticStackExample;

const
  MAX = 128;  // Maximum size of the stack

type
  TStack = record
    data: array[1..MAX] of Integer;
    top: Integer;
  end;

var
  stack: TStack;

// Initialize the stack
procedure Initialize(var s: TStack);
begin
  s.top := 0;
end;

// Push an element onto the stack
procedure Push(var s: TStack; value: Integer);
begin
  if s.top < MAX then
  begin
    Inc(s.top);
    s.data[s.top] := value;
  end
  else
    WriteLn('Stack Overflow!');
end;

// Pop an element from the stack
function Pop(var s: TStack): Integer;
begin
  if s.top > 0 then
  begin
    Pop := s.data[s.top];
    Dec(s.top);
  end
  else
  begin
    WriteLn('Stack Underflow!');
    Pop := -1;  // Return an invalid value
  end;
end;

// Check if the stack is empty
function IsEmpty(s: TStack): Boolean;
begin
  IsEmpty := s.top = 0;
end;

// Print all elements in the stack
procedure PrintStack(s: TStack);
var
  i: Integer;
begin
  if IsEmpty(s) then
    WriteLn('Stack is empty.')
  else
  begin
    WriteLn('Stack contents (top to bottom):');
    for i := s.top downto 1 do
      WriteLn('  ', s.data[i]);
  end;
end;

begin
  Initialize(stack);
  
  Push(stack, 10);
  Push(stack, 20);
  Push(stack, 30);  
  Push(stack, 40);
  Push(stack, 50);
  
  WriteLn('Popped: ', Pop(stack));  
  WriteLn('Popped: ', Pop(stack));  

  PrintStack(stack);
end.




(*
run:
  
Popped: 50
Popped: 40
Stack contents (top to bottom):
  30
  20
  10

*)



answered Aug 14, 2025 by avibootz
...