in CO and Architecture retagged by
103 views
0 votes
0 votes
Write a stack-based program that computes the following function : 5+(3x7) – 8, assuming that the stack starts out empty
in CO and Architecture retagged by
103 views

1 Answer

0 votes
0 votes

@shima+abdullah

 

 In forth you could do it this way….

1.  5 3 7 * + 8 –

 

What is happening on the line :: 

 

  1.   5 is pushed onto the stack....

  2.   3 is pushed onto the stack….

  3.   7 is pushed onto the stack….

  4.   * multiplies the top two stack elements which removes them both from the stack and then pushes the result onto the stack……

  5.  + adds the top two stack elements which removes them both from the stack and then pushes the result onto the stack…..

  6.  8 is pushed onto the stack….

  7.  - the top element is subtracted from second element which removes them both from the stack and then pushes the result onto the stack….

 

So the stack looks like this at each stage.

Top of the stack is the rightmost element ::

#      5 ...

##    5 3 ...

###  5 3 7 ...

####  5 21 ...

#####  26 ...

######  26 8 ….

#######  18 …..

 

The . on the second line is a command that prints the top of the stack and then removes it ….

 

## assuming that the stack starts out empty?

Also, in the above code it does not matter if there is something in the stack before these operations as we only play with what we put there….

 

 

 

Related questions