<ul>
<li>In Australia at least, many supermarkets store shopping trolleys in a dead-end corral. So when you get a trolley for your shopping it will be the last one someone previously pushed into the corral.</li>
<li>The paper into a photocopier tray</li>
<li>For a Biblical reference: <a href="http://biblehub.com/matthew/20-16.htm" rel="nofollow noreferrer">Matthew 20:16</a></li>
<li>The way many of us process interruptions. We pause one task to focus on the interruption. We might pause that task to work on a subsequent interruption. Repeat for as many levels as you want. And then as each task is completed we return to the previous interrupt level.</li>
</ul>

CC BY-SA 3.0
2017-06-19T03:06:01.750Z
Welcome to CSE! Good example about processing interruptions.  But isn't Matthew 20:16 really more of an example of list reversal? ;-)  I hope we'll hear more from you in the future.
Ben I.
CC BY-SA 3.0
2017-06-19T02:35:23.587Z
2017-06-19T03:06:09.273Z
2017-06-19T03:06:09.273Z
MattClarke
<h1>The call stack</h1>

<p>They've presumably already learned about functions, so if you use that as the example, you both teach them about stacks <em>and</em> give them a deeper understanding of how functions work.</p>

<p>I would take it in two main phases, using code similar to this as an example.</p>

<pre><code>h(c) {
    print(c)
    return
}

g(b) {
    h(b + 3)
    print("foo")
    return
}

f(a) {
   x = 42
   g(x)
   h(x)
   print("bar")
   return
}
</code></pre>

<p>First, focus on how the return always knows to transfer control to the statement after the line the function was called on.  So for instance, the return from <code>h</code> might go to either <code>g</code> or <code>f</code>, depending on where it was called from, and in the former case, <code>g</code> in turn knows where <em>it</em> was called from.  If the language they're using is one that prints the call stack when it crashes, they're probably already somewhat familiar with this.  </p>

<p>Make sure they fully understand how the control flow works first, then bring in the concept of a stack and explain how you can implement function calls by storing the return addresses on the stack whenever you call a function, and popping them whenever you return.</p>

<p>Once they understand that, you <em>might</em> want to proceed to explain how parameters are stored on the stack.  That might confuse them a bit, though, since you can't access elements other than the one on top in a "theoretically pure" stack, but you do when accessing values in the stack frame. I would probably just mention to them that the reality is a bit more complicated than what you just described, but save the details for a later lesson.</p>

CC BY-SA 3.0
2017-06-20T01:50:41.263Z
2017-06-20T01:50:41.263Z
Ray
<p>A stack can be used to verify that an HTML document is well-formed.  You begin with an empty stack.</p>

<p>When a tag opens (say &lt;p&gt;), the tag's type, in this case, "p", onto the stack.</p>

<p>When a tag is self-closing, do nothing.</p>

<p>When a tag closes, (say &lt;/p&gt;), check to see that it matches the tag on the top of the stack by peeking at it.  If there is a match, pop the stack.  If there is a mismatch, emit an error message telling where the error lurks in the HTML file you are scanning.</p>

<p>If, at any time in the process you find an empty stack, report an error.</p>

<p>At the end:</p>

<p>If there are still tags on the stack, you have unclosed tags; report an error.</p>

<p>If the stack is empty, your HTML file has balanced tags. </p>

CC BY-SA 3.0
2017-06-20T21:33:41.320Z
2017-06-20T21:33:41.320Z
ncmathsadist
<p>I am not a computer science educator at all, but this question immediately reminded me of Leo Brodie's book <em>Starting Forth</em> from 1981 (!) with some cute <a href="https://www.forth.com/starting-forth/1-forth-stacks-dictionary/#The_Stack_Forth8217s_Workspace_for_Arithmetic" rel="nofollow noreferrer">visualizations of stack manipulations</a>. This links up with @Dubu's answer about <em>the PostScript language</em>.</p>

CC BY-SA 3.0
2017-06-19T14:53:57.650Z
2017-06-19T14:53:57.650Z
Draakhond
<p>A refrigerator: You put food in the freezer. To take out oldest food, first, you need to take out all newer food.</p>

CC BY-SA 4.0
2018-11-19T23:11:38.473Z
2018-11-20T00:22:59.443Z
2018-11-20T00:22:59.443Z
Jason Huh
<p>Packing a suitcase:  the items last to be packed are the first to come out (assuming you place items directly on top of each other)</p>

<p>A couple of others:
-- A stack of papers
-- A stack of chairs</p>

CC BY-SA 3.0
2017-06-20T05:39:29.027Z
This answer could really benefit from more explanation. Could you add some explanation to how those examples are a stack?
ItamarG3
CC BY-SA 3.0
2017-06-20T05:29:54.547Z
2017-06-20T05:29:54.547Z
rimsky
<p>History in your browser, recurrence in functions, &quot;undo&quot; like control-z in many programs are examples of stack usage</p>

CC BY-SA 4.0
2021-04-24T11:43:40.370Z
2021-04-24T11:43:40.370Z
Kraken
<p>I once had to implement a limited undo function (undo changes to the current field, or addition/deletion of records).</p>

<p>The lists of undo deltas (one for field changes and one for records) were stored as stacks.</p>

CC BY-SA 3.0
2017-06-18T16:27:24.900Z
Wow, that's a great example! I love it!
Yotam Salmon
CC BY-SA 3.0
2017-06-18T16:25:17.877Z
2017-06-18T16:25:17.877Z
James McLeod
<p>I like the pez dispenser.</p>

<p>Also the stack of papers (where the actual human interaction is never to take the top item but rather to take the second from the top.</p>

<p>At some point you have to talk about pancakes and the fact that people don't actually eat them as a stack -- they frequently destroy stack integrity by cutting top to bottom. I personally use a stack of pancakes as a queue, extracting one at a time from the btotom as it soaks up syrup but I've been told I'm an odd one :-)</p>

CC BY-SA 3.0
2017-06-18T11:47:19.683Z
I treat pancakes as stack, popping the top one off and dunking it in the syrup that's sitting on the side. But that might just be me. :)
Scimonster
CC BY-SA 3.0
2017-06-18T11:54:42.403Z
Pancakes as a stack or as a queue -- is there anything they can't do???? :-)
Mike Zamansky
CC BY-SA 3.0
2017-06-18T11:59:25.417Z
Stack, or queue, doesn't matter much, they get consumed either way. That's something that's usually left out of stack lessons: that the stack is consumed. As to pancakes and what can't they do: Survive long on my plate. :)
Gypsy Spellweaver
CC BY-SA 3.0
2017-06-18T11:41:13.910Z
2017-06-18T11:41:13.910Z
Mike Zamansky
<p>A stack of trays in a cafeteria. I also like the pole of rings analogy.</p>

<p>With the trays, you can pop (take a tray) and push (return it when you're done). You can see what the top tray (first item) is (ex. what color), and see if the stack is empty. Non-stack operations such as getting a count of the trays are non-trivial. It is also impossible to insert or remove a tray from a random position.</p>

CC BY-SA 3.0
2017-06-18T14:41:47.530Z
The spring-loaded stack of trays in a (university) cafeteria was in fact the origin of the name of the data structure, at least according to common legend.
Jörg W Mittag
CC BY-SA 3.0
2017-06-19T08:54:11.060Z
I had an A-Level computing teacher who got so carried away with explaining the mechanism of the stack of plates he forgot that he was supposed to actually be explaining a stack in computing terms.
Muzer
CC BY-SA 3.0
2017-06-18T11:34:05.910Z
2017-06-18T12:19:36.753Z
2017-06-18T12:19:36.753Z
Scimonster
<p>A rather interesting analogy is that of a firearms magazine. </p>

<p>if we look at this picture:</p>

<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0a/Caroline-chargeur-plein-p1000499b.jpg/157px-Caroline-chargeur-plein-p1000499b.jpg" alt="a magazine"></p>

<p>It is easy to see that bullets can be inserted from the top, and only the topmost bullet is accessible. Such is a stack. A magazine works by LIFO (Last In First Out), and so does a Stack. </p>

<p>Furthermore, the four (five<sup>1</sup>) basic operations of a Stack are applicable: </p>

<ol>
<li>Push - adding a new element (bullet) to the top.</li>
<li>Pop - remove the top element (bullet) from the stack (in the analogy, this is like shooting).</li>
<li>Peek - looking at the first element of the stack (checking to make sure that the topmost bullet is correctly placed)</li>
<li>Check if Empty - check if the stack is empty (in the analogy, this operation is checking if there are bullets left)<br></li>
<li>(Initializing the stack - creating a new stack)</li>
</ol>

<p><sup>1</sup>The initializing of the stack isn't exactly a special operation a stack can do.</p>

<p>A stack is something used in programming when you need to keep a record of the history of versions. For example, many text editors use a stack data structure to save the changes made to the file. Also, revisions of posts on Stack Exchange have some form of a Stack (funny coincidence, isn't it?) to save the revisions (though I think the SE system uses partial functionality of a stack. I'll check that and edit this post when I have a definite answer about this particular part).</p>

<p>The very obvious usage of stack is, of course, the stack segment of computer memory. The call stack is, well, a call <strong>stack</strong>. (more on this can be seen <a href="http://jcsites.juniata.edu/faculty/kruse/cs240/images/stacka1.gif" rel="noreferrer">here</a>)</p>

<p>Another handy example is the browser back button. The browser has a stack with the links (technically, sort of cached versions) of pages you've been to. When pressing the "back" button, the stack's <code>pop</code> function is called, and you get redirected to that. When a link is pressed, a new element is <code>pushed</code> onto the stack. </p>

CC BY-SA 3.0
2017-06-18T12:41:34.307Z
Of course, but that's the *definition* of the stack. I'll definitely explain that as an origin to the name of the stack, but I need some use-cases for programming and life. (I hope I'm clear enough)
Yotam Salmon
CC BY-SA 3.0
2017-06-18T12:44:00.420Z
@YotamSalmon then you should write that in your question. I'll edit my answer soon.
ItamarG3
CC BY-SA 3.0
2017-06-18T12:59:12.367Z
@YotamSalmon edited the answer :)
ItamarG3
CC BY-SA 3.0
2017-06-18T17:32:41.013Z
I would definitely mention the browser's back button. It provides a non-metaphorical example, that's easy to understand, and demonstratively proves that stacks are useful in programming.
Phoenix
CC BY-SA 3.0
2017-07-19T11:23:28.353Z
Since the bullets are identical to each other, this analogy loses me. Although a stack matches the physical mechanism it is more complicated than necessary to model the purpose of the magazine.
James McLeod
CC BY-SA 3.0
2017-07-19T11:59:29.413Z
@JamesMcLeod bullets are not identical in the sense that calling the java `.equals()` would return `false`. They are *instances* of `Bullet`, but are no more the same than two people.
ItamarG3
CC BY-SA 4.0
2018-11-17T01:56:28.763Z
Some people might find your example triggering.
Ellen Spertus
CC BY-SA 4.0
2018-11-17T07:36:57.800Z
@EllenSpertus If that's a pun, I like it. If it's unintended, then I'll say this: My answer isn't meant to trigger anyone.
ItamarG3
CC BY-SA 3.0
2017-06-18T11:54:22.643Z
2017-06-18T12:56:04.297Z
2017-06-18T12:56:04.297Z
ItamarG3
<p>The back button on a web browser is an excellent example of a stack implementation that is easily understood even by non-experts and easily demonstrated in a class.  You can illustrate the stack in diagrams, and you can show it in action in a browser.</p>

<p>When a user visits a new web page, the current page gets pushed onto the stack.  When the user clicks the back button, the last page pushed onto the stack is popped off of the stack and loaded in the browser window.  When all of the pages are popped off of the stack, the back button grays out, indicating that the stack is empty.</p>

<p>Note that the forward button also uses a stack, but it works on a slightly different basis.  Clicking the back button pushes the current page on the stack and clicking the forward button pops the top page off of the stack.  Visiting a new page without clicking either button automatically empties the forward button stack.</p>

CC BY-SA 3.0
2017-06-19T18:51:08.093Z
This is an excellent, intuitive example.  Welcome to CSE!  I hope we hear more from you in the future.
Ben I.
CC BY-SA 3.0
2017-09-08T07:10:14.470Z
Excellent!! This is only example which is comprehensible to a common man!!
Failed Scientist
CC BY-SA 3.0
2017-06-19T18:40:32.430Z
2017-06-19T18:40:32.430Z
Bart Shoulars
<p><strong>Check whether a string of parentheses is balanced or not</strong>. </p>

<p>For example, return <code>True</code> for these input strings:</p>

<p><code>(()())
([]{{}}[])
</code></p>

<p>but <code>False</code> for these strings:</p>

<p><code>(()
([)(])
</code></p>

<p>You can solve this using recursion, but a very efficient and clear solution would be to iterate over the string, whenever you encounter an opening symbol, you <code>push</code> it into the stack. Whenever you encounter a closing symbol you <code>pop</code> from the stack and check that that the types match.</p>

<p>See <a href="http://interactivepython.org/runestone/static/pythonds/BasicDS/SimpleBalancedParentheses.html" rel="noreferrer">here for a Python implementation</a></p>

CC BY-SA 3.0
2017-06-19T19:53:50.620Z
I run this lab every year. I can vouch that it's a good lab :)  Welcome to CSE!  I hope we hear more from you in the future!
Ben I.
CC BY-SA 3.0
2018-04-27T11:15:08.780Z
It's worth noting that recursive solution is really the same, just using underlying call stack - so it's not explicitly visible.
Frax
CC BY-SA 3.0
2017-06-19T19:52:21.700Z
2017-06-19T19:52:21.700Z
Ofri Raviv
<p>The "real-life" examples are pretty clearly delineated here already, but since you asked for examples in programming as well, I'll add one to the list. </p>

<p>Stacks can be used to build calculators. There's a great assignment in CS50 AP called <a href="http://docs.cs50.net/2016/ap/problems/calc/2/calc2.html" rel="nofollow noreferrer">Calc 2.0</a>. Students build a command-line calculator in C using a stack to store the numbers passed in by the user. Additionally, it's an opportunity to teach students about prefix notion as opposed to their normal use of infix notation.</p>

<p>The problem specification explains why this approach is worth pursuing:</p>

<blockquote>
  <p>Visually, this approach of "finding the rightmost operator
  and applying it to the two numbers to its right" is an intuitive way
  for humans to parse prefix notation, but computers can be a bit
  smarter about this, without ever having to look at each operand or
  operator more than once, if instead we store all the information in a
  stack as we see it.</p>
  
  <p>If the computer parsed this input by starting at the right side (aka
  the last element of <code>argv</code>) and pushing numbers onto a stack as it came
  across them, then when it came upon an operation all that would need
  to happen is to pop the top two numbers off the stack, apply the
  operation, and push the result back on!</p>
</blockquote>

<p>Here is the boilerplate they are given for building a stack:</p>

<pre><code>typedef struct
{
   int size;
   float nums[MAXNUMS];
}
stack;
</code></pre>

<p>It's a simple struct, but since students can easily error-check their own work with simple math, this assignment provides a great way to actually start using a stack for something meaningful that also builds on students' prior knowledge. </p>

CC BY-SA 3.0
2017-07-12T12:13:16.553Z
You can, of course, use postfix as well and show the workings of a RPN (Reverse Polish Notation) calculator such as the HP15C, my all time favorite calculator. 3 4 5 * + yields 23.
Buffy
CC BY-SA 3.0
2017-06-18T14:50:43.873Z
2017-06-18T17:04:05.197Z
2017-06-18T17:04:05.197Z
Peter
<p>In practice, many calculators employ the <a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm" rel="nofollow noreferrer">Shunting Yard algorithm</a> to evaluate mathematical expressions as per the rules of BODMAS. The algorithm makes use of stacks to push and pop operators based on precedence and position.</p>

CC BY-SA 3.0
2017-06-18T17:56:31.410Z
It's a nice example to be sure, but if you try this with your class, be aware that Shunting Yard can be tricky for kids who are just at the point where they are learning about stacks.  You have to break this one down very carefully for them.
Ben I.
CC BY-SA 3.0
2017-06-19T16:24:46.310Z
You can always start with the analogous railroad junction and talk about how you have to re-order the cars in a way that's easier to evaluate programmatically.
Patrick Roberts
CC BY-SA 3.0
2017-06-18T16:52:53.563Z
2017-07-12T11:22:52.233Z
2017-07-12T11:22:52.233Z
Y.S.
<p>This won't work for all students, but some will likely be familiar with the very popular collectable card game <a href="https://en.wikipedia.org/wiki/Magic:_The_Gathering" rel="noreferrer">Magic: The Gathering</a>.</p>

<p>In this game, spells are cast to <strong>"the stack"</strong>, with the last spell cast resolving first.  During resolution of the stack, more spells may be cast to the top of the stack.</p>

CC BY-SA 3.0
2017-06-19T14:38:17.617Z
2017-06-19T14:38:17.617Z
James
<p>In my view, a good computer science example for stack-oriented processing is <a href="https://en.wikipedia.org/wiki/PostScript#The_language" rel="nofollow noreferrer">the PostScript language</a>. </p>

<p>The <code>Hello world</code> example from the Wikipedia page shows the Reverse Polish (postfix) notation used in PostScript (similar to the <a href="http://docs.cs50.net/2016/ap/problems/calc/2/calc2.html" rel="nofollow noreferrer">CS50 AP Calc 2.0</a> Peter showed in his answer that uses prefix notation):</p>

<pre><code>%!PS
 /Courier             % name the desired font
 20 selectfont        % choose the size in points and establish 
                      % the font as the current one
 72 500 moveto        % position the current point at 
                      % coordinates 72, 500 (the origin is at the 
                      % lower-left corner of the page)
 (Hello world!) show  % stroke the text in parentheses
 showpage             % print all on the page
</code></pre>

<p>Input tokens would be pushed on a stack as they are parsed, and when an operator or command is encountered that needs <em>n</em> arguments, the upper <em>n</em> tokens would be popped from the stack, used for calculation or function execution and any result pushed on the stack again. </p>

<p>This can even better be seen in the example that draws a line, using a conversion from PostScript points to millimeters:</p>

<pre><code>/mm {360 mul 127 div} def
 0 0 moveto
 0 40 mm lineto stroke
</code></pre>

<p>The first line defines¹ a conversion function <code>mm</code> which is used in the third line to draw a vertical line 40 mm long. The function pops the top element from the stack, multiplies it with 360, divides it by 127 and pushes the result on the stack again.</p>

<hr>

<p>¹ In fact, the <code>def</code> command, which defines a function, will <em>not</em> put its result back on the stack but into a dictionary which is used to look up commands.</p>

CC BY-SA 3.0
2017-06-19T13:07:50.237Z
Welcome to cseducators! This is a very nice use-case. I hope we hear more from you in the future.
Ben I.
CC BY-SA 3.0
2017-07-12T12:07:58.663Z
I note that postscript is built on a Forth language base. Forth itself is stack oriented.
Buffy
CC BY-SA 3.0
2017-06-19T13:01:13.453Z
2017-06-19T13:01:13.453Z
Dubu
<p>Much of what has been said already is wonderful.  I would like to point out that Mike's Pez dispenser visualization is brilliant, and lends itself to a direct lesson with manipulables.  You can take a few of them into an actual classroom, mix up various Pez colors, and show all of the standard operations of a stack in a way that they can physically play with.  <code>Pop</code>, <code>push</code>, <code>peek</code>, and <code>isEmpty</code> are all clearly defined operations in a real life Pez dispenser.</p>

<p>Let the kids wash their hands, and then use tiny bits of paper that the kids write on and place on top of a pez brick prior to loading it into the dispenser, and you will have a natural toy with all of the standard operations.  And it goes without saying that the kids will love to eat the results of each <code>pop</code> operation as they sort out their algorithms.  :)</p>

<p>I also wanted to add that if your kids are familiar with linked lists, that is a great way to show a stack implementation.</p>

<p>Where stacks matter a tremendous amount in my instruction is in AP Computer Science A when talking about variable storage and scope, and in our Data Structures course when we talk about how function calls operate.</p>

CC BY-SA 3.0
2017-06-18T18:02:57.180Z
2017-06-19T01:51:17.890Z
2017-06-19T01:51:17.890Z
Ben I.
<p>Here are couple of examples which don't employ objects resembling real-life stack:</p>

<ul>
<li>Russian doll (matryoshka).  It is a stack if you use the relationship <code>contained_in(BiggerDoll, SmallerDoll)</code> as a model for stack.  <code>push</code> in this context would be equivalent to encasing a stack of Russian dolls in a yet bigger Russian doll, <code>pop</code> would be equivalent to opening the outermost doll and extracting the remaining dolls.</li>
<li>Literary figure "story within a story" (or "dream within a dream"), although the analogy is a little imprecise since any "inner" story can be observed from an "outer" story.  The examples of such stories are plentiful, but since this should appeal to high-school students, I think, the movie Inception (the one starring DiCaprio) could be used. In this movie, the <code>push</code> is when the characters enter a dream, and <code>pop</code> is when they wake up from the dream.  Characters must wake up from their dreams in the exact reverse order from the one in which they entered them.</li>
<li>Palindrome.  I.e. the way to recognize one by <code>push</code>ing half of it on a stack and then <code>pop</code>ing the other half.</li>
</ul>

CC BY-SA 3.0
2017-06-19T11:24:52.317Z
Welcome to Computer Science Educators! Could you add some details on how the first two are an example of a stack?
ItamarG3
CC BY-SA 3.0
2017-06-19T11:31:41.183Z
@ItamarGreen OK.
wvxvw
CC BY-SA 3.0
2017-06-19T11:37:23.613Z
The first example really is a **very** good one.
ItamarG3
CC BY-SA 3.0
2017-06-19T11:12:34.483Z
2017-06-19T11:31:30.493Z
2017-06-19T11:31:30.493Z
wvxvw
<p>I'm looking for examples to give my students when lecturing about stacks, for use-cases of the stack in programming and life.</p>

<p>So far I've been thinking of a pole of rings (when you can insert or remove rings from the top).</p>

<p>My students are high school students I'm teaching next year for their matriculation exam. They have only some basic knowledge in procedural programming and the tip of the iceberg in Object-Oriented stuff.</p>

<p>Any ideas for more analogies or examples?</p>

CC BY-SA 3.0
2017-06-18T11:42:56.623Z
Could you please add a context? What is the level of the students?
ItamarG3
CC BY-SA 3.0
2017-06-18T12:44:00.463Z
High school students I'm teaching next year for their בגרות exam. They have only some  basic knowledge in procedural programming and the tip of the iceberg in Object-Oriented stuff.
Yotam Salmon
CC BY-SA 3.0
2017-06-18T12:44:59.343Z
Again, you need to write these things in the question itself. BTW, בגרות are called matriculation exams (or finals) in english ;)
ItamarG3
CC BY-SA 3.0
2017-06-18T12:48:06.897Z
I knew about the word "matriculation", just wasn't sure if those exams are actually known by this name (I have never heard anyone using this word in English so I wasn't confident about using it). Added the info to the question, thank you for the tip.
Yotam Salmon
CC BY-SA 3.0
2017-06-18T17:06:32.270Z
Note that these analogies [can be very confusing](https://cs.stackexchange.com/q/76871/40243) to some people.
isanae
CC BY-SA 3.0
2017-06-18T18:17:27.197Z
@nocomprende Yes, it's based on the same idea
Yotam Salmon
CC BY-SA 3.0
2017-06-19T12:38:48.720Z
Forth language (or derivatives). Maybe it's worth a try to implement a very simple interpreter of a very simple subset of it.
Display Name
CC BY-SA 3.0
2017-06-19T16:20:09.267Z
While it's not an analogy, an interesting real-world use-case is [infix-expression parsing](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) **Edit** whoops, just saw [this answer](https://cseducators.stackexchange.com/a/804/1019). I recommend something like that so as to minify confusion. Fabricated scenarios seem like bad examples to use in my opinion, but you can always incorporate the analogous railroad junction.
Patrick Roberts
CC BY-SA 3.0
2017-06-20T08:34:24.923Z
A real life example we used in our CS classes (even let the students implement a sorting algorithm with it) is a siding (rail) for waggons. Unless using cranes you can only push/pop waggons at these. Although you could easily peek the second waggon in line.
Aron_dc
CC BY-SA 4.0
2018-11-27T13:31:32.933Z
The unwashed clothes on the floor of a teenagers bedroom.
pojo-guy
<teaching-analogy><data-structure>
What are some good examples of using a stack data structure?
# What are some good examples of using a stack data structure?

(Asked by: username_0 on 2017-06-18)

I'm looking for examples to give my students when lecturing about stacks, for use-cases of the stack in programming and life.

So far I've been thinking of a pole of rings (when you can insert or remove rings from the top).

My students are high school students I'm teaching next year for their matriculation exam. They have only some basic knowledge in procedural programming and the tip of the iceberg in Object-Oriented stuff.

Any ideas for more analogies or examples?

**Tags:** teaching-analogy, data-structure

> **Comments:**
> **username_1**: Could you please add a context? What is the level of the students?  
> **username_0**: High school students I'm teaching next year for their בגרות exam. They have only some  basic knowledge in procedural programming and the tip of the iceberg in Object-Oriented stuff.  
> **username_1**: Again, you need to write these things in the question itself. BTW, בגרות are called matriculation exams (or finals) in english ;)  
> **username_0**: I knew about the word "matriculation", just wasn't sure if those exams are actually known by this name (I have never heard anyone using this word in English so I wasn't confident about using it). Added the info to the question, thank you for the tip.  
> **username_2**: Note that these analogies [can be very confusing](https://cs.stackexchange.com/q/76871/40243) to some people.  
> **username_0**: @nocomprende Yes, it's based on the same idea  
> **username_3**: Forth language (or derivatives). Maybe it's worth a try to implement a very simple interpreter of a very simple subset of it.  
> **username_4**: While it's not an analogy, an interesting real-world use-case is [infix-expression parsing](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) **Edit** whoops, just saw [this answer](https://cseducators.stackexchange.com/a/804/1019). I recommend something like that so as to minify confusion. Fabricated scenarios seem like bad examples to use in my opinion, but you can always incorporate the analogous railroad junction.  
> **username_5**: A real life example we used in our CS classes (even let the students implement a sorting algorithm with it) is a siding (rail) for waggons. Unless using cranes you can only push/pop waggons at these. Although you could easily peek the second waggon in line.  
> **username_6**: The unwashed clothes on the floor of a teenagers bedroom.  

---

## 19 answers

### Answer by username_15 on 2017-06-18. Score: 24 | Accepted answer

I once had to implement a limited undo function (undo changes to the current field, or addition/deletion of records).

The lists of undo deltas (one for field changes and one for records) were stored as stacks.

> **Comments:**
> **username_0**: Wow, that's a great example! I love it!  

---

### Answer by username_17 on 2017-06-18. Score: 17

A stack of trays in a cafeteria. I also like the pole of rings analogy.

With the trays, you can pop (take a tray) and push (return it when you're done). You can see what the top tray (first item) is (ex. what color), and see if the stack is empty. Non-stack operations such as getting a count of the trays are non-trivial. It is also impossible to insert or remove a tray from a random position.

> **Comments:**
> **username_19**: The spring-loaded stack of trays in a (university) cafeteria was in fact the origin of the name of the data structure, at least according to common legend.  
> **username_20**: I had an A-Level computing teacher who got so carried away with explaining the mechanism of the stack of plates he forgot that he was supposed to actually be explaining a stack in computing terms.  

---

### Answer by username_1 on 2017-06-18. Score: 16

A rather interesting analogy is that of a firearms magazine.

if we look at this picture:

![a magazine](https://upload.wikimedia.org/wikipedia/commons/thumb/0/0a/Caroline-chargeur-plein-p1000499b.jpg/157px-Caroline-chargeur-plein-p1000499b.jpg)

It is easy to see that bullets can be inserted from the top, and only the topmost bullet is accessible. Such is a stack. A magazine works by LIFO (Last In First Out), and so does a Stack.

Furthermore, the four (five1) basic operations of a Stack are applicable:

1. Push - adding a new element (bullet) to the top.
2. Pop - remove the top element (bullet) from the stack (in the analogy, this is like shooting).
3. Peek - looking at the first element of the stack (checking to make sure that the topmost bullet is correctly placed)
4. Check if Empty - check if the stack is empty (in the analogy, this operation is checking if there are bullets left)
5. (Initializing the stack - creating a new stack)

1The initializing of the stack isn't exactly a special operation a stack can do.

A stack is something used in programming when you need to keep a record of the history of versions. For example, many text editors use a stack data structure to save the changes made to the file. Also, revisions of posts on Stack Exchange have some form of a Stack (funny coincidence, isn't it?) to save the revisions (though I think the SE system uses partial functionality of a stack. I'll check that and edit this post when I have a definite answer about this particular part).

The very obvious usage of stack is, of course, the stack segment of computer memory. The call stack is, well, a call **stack**. (more on this can be seen [here](http://jcsites.juniata.edu/faculty/kruse/cs240/images/stacka1.gif))

Another handy example is the browser back button. The browser has a stack with the links (technically, sort of cached versions) of pages you've been to. When pressing the "back" button, the stack's `pop` function is called, and you get redirected to that. When a link is pressed, a new element is `pushed` onto the stack.

> **Comments:**
> **username_0**: Of course, but that's the *definition* of the stack. I'll definitely explain that as an origin to the name of the stack, but I need some use-cases for programming and life. (I hope I'm clear enough)  
> **username_1**: @YotamSalmon then you should write that in your question. I'll edit my answer soon.  
> **username_1**: @YotamSalmon edited the answer :)  
> **username_21**: I would definitely mention the browser's back button. It provides a non-metaphorical example, that's easy to understand, and demonstratively proves that stacks are useful in programming.  
> **username_15**: Since the bullets are identical to each other, this analogy loses me. Although a stack matches the physical mechanism it is more complicated than necessary to model the purpose of the magazine.  
> **username_1**: @username_30McLeod bullets are not identical in the sense that calling the java `.equals()` would return `false`. They are *instances* of `Bullet`, but are no more the same than two people.  
> **username_22**: Some people might find your example triggering.  
> **username_1**: @EllenSpertus If that's a pun, I like it. If it's unintended, then I'll say this: My answer isn't meant to trigger anyone.  

---

### Answer by username_23 on 2017-06-19. Score: 15

The back button on a web browser is an excellent example of a stack implementation that is easily understood even by non-experts and easily demonstrated in a class. You can illustrate the stack in diagrams, and you can show it in action in a browser.

When a user visits a new web page, the current page gets pushed onto the stack. When the user clicks the back button, the last page pushed onto the stack is popped off of the stack and loaded in the browser window. When all of the pages are popped off of the stack, the back button grays out, indicating that the stack is empty.

Note that the forward button also uses a stack, but it works on a slightly different basis. Clicking the back button pushes the current page on the stack and clicking the forward button pops the top page off of the stack. Visiting a new page without clicking either button automatically empties the forward button stack.

> **Comments:**
> **username_8**: This is an excellent, intuitive example.  Welcome to CSE!  I hope we hear more from you in the future.  
> **username_24**: Excellent!! This is only example which is comprehensible to a common man!!  

---

### Answer by username_25 on 2017-06-19. Score: 14

**Check whether a string of parentheses is balanced or not**.

For example, return `True` for these input strings:

`(()())
([]{{}}[])`

but `False` for these strings:

`(()
([)(])`

You can solve this using recursion, but a very efficient and clear solution would be to iterate over the string, whenever you encounter an opening symbol, you `push` it into the stack. Whenever you encounter a closing symbol you `pop` from the stack and check that that the types match.

See [here for a Python implementation](http://interactivepython.org/runestone/static/pythonds/BasicDS/SimpleBalancedParentheses.html)

> **Comments:**
> **username_8**: I run this lab every year. I can vouch that it's a good lab :)  Welcome to CSE!  I hope we hear more from you in the future!  
> **username_26**: It's worth noting that recursive solution is really the same, just using underlying call stack - so it's not explicitly visible.  

---

### Answer by username_16 on 2017-06-18. Score: 10

I like the pez dispenser.

Also the stack of papers (where the actual human interaction is never to take the top item but rather to take the second from the top.

At some point you have to talk about pancakes and the fact that people don't actually eat them as a stack -- they frequently destroy stack integrity by cutting top to bottom. I personally use a stack of pancakes as a queue, extracting one at a time from the btotom as it soaks up syrup but I've been told I'm an odd one :-)

> **Comments:**
> **username_17**: I treat pancakes as stack, popping the top one off and dunking it in the syrup that's sitting on the side. But that might just be me. :)  
> **username_16**: Pancakes as a stack or as a queue -- is there anything they can't do???? :-)  
> **username_18**: Stack, or queue, doesn't matter much, they get consumed either way. That's something that's usually left out of stack lessons: that the stack is consumed. As to pancakes and what can't they do: Survive long on my plate. :)  

---

### Answer by username_27 on 2017-06-18. Score: 7

The "real-life" examples are pretty clearly delineated here already, but since you asked for examples in programming as well, I'll add one to the list. 
Stacks can be used to build calculators. There's a great assignment in CS50 AP called Calc 2.0. Students build a command-line calculator in C using a stack to store the numbers passed in by the user. Additionally, it's an opportunity to teach students about prefix notion as opposed to their normal use of infix notation.
The problem specification explains why this approach is worth pursuing:

Visually, this approach of "finding the rightmost operator
  and applying it to the two numbers to its right" is an intuitive way
  for humans to parse prefix notation, but computers can be a bit
  smarter about this, without ever having to look at each operand or
  operator more than once, if instead we store all the information in a
  stack as we see it.
If the computer parsed this input by starting at the right side (aka
  the last element of argv) and pushing numbers onto a stack as it came
  across them, then when it came upon an operation all that would need
  to happen is to pop the top two numbers off the stack, apply the
  operation, and push the result back on!

Here is the boilerplate they are given for building a stack:
typedef struct
{
   int size;
   float nums[MAXNUMS];
}
stack;

It's a simple struct, but since students can easily error-check their own work with simple math, this assignment provides a great way to actually start using a stack for something meaningful that also builds on students' prior knowledge.

> **Comments:**
> **username_28**: You can, of course, use postfix as well and show the workings of a RPN (Reverse Polish Notation) calculator such as the HP15C, my all time favorite calculator. 3 4 5 * + yields 23.  

---

### Answer by username_29 on 2017-06-18. Score: 6

In practice, many calculators employ the [Shunting Yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) to evaluate mathematical expressions as per the rules of BODMAS. The algorithm makes use of stacks to push and pop operators based on precedence and position.

> **Comments:**
> **username_8**: It's a nice example to be sure, but if you try this with your class, be aware that Shunting Yard can be tricky for kids who are just at the point where they are learning about stacks.  You have to break this one down very carefully for them.  
> **username_4**: You can always start with the analogous railroad junction and talk about how you have to re-order the cars in a way that's easier to evaluate programmatically.  

---

### Answer by username_30 on 2017-06-19. Score: 5

This won't work for all students, but some will likely be familiar with the very popular collectable card game [Magic: The Gathering](https://en.wikipedia.org/wiki/Magic:_The_Gathering).

In this game, spells are cast to **"the stack"**, with the last spell cast resolving first. During resolution of the stack, more spells may be cast to the top of the stack.


---

### Answer by username_8 on 2017-06-18. Score: 4

Much of what has been said already is wonderful. I would like to point out that Mike's Pez dispenser visualization is brilliant, and lends itself to a direct lesson with manipulables. You can take a few of them into an actual classroom, mix up various Pez colors, and show all of the standard operations of a stack in a way that they can physically play with. `Pop`, `push`, `peek`, and `isEmpty` are all clearly defined operations in a real life Pez dispenser.

Let the kids wash their hands, and then use tiny bits of paper that the kids write on and place on top of a pez brick prior to loading it into the dispenser, and you will have a natural toy with all of the standard operations. And it goes without saying that the kids will love to eat the results of each `pop` operation as they sort out their algorithms. :)

I also wanted to add that if your kids are familiar with linked lists, that is a great way to show a stack implementation.

Where stacks matter a tremendous amount in my instruction is in AP Computer Science A when talking about variable storage and scope, and in our Data Structures course when we talk about how function calls operate.


---

### Answer by username_32 on 2017-06-19. Score: 4

Here are couple of examples which don't employ objects resembling real-life stack:

* Russian doll (matryoshka). It is a stack if you use the relationship `contained_in(BiggerDoll, SmallerDoll)` as a model for stack. `push` in this context would be equivalent to encasing a stack of Russian dolls in a yet bigger Russian doll, `pop` would be equivalent to opening the outermost doll and extracting the remaining dolls.
* Literary figure "story within a story" (or "dream within a dream"), although the analogy is a little imprecise since any "inner" story can be observed from an "outer" story. The examples of such stories are plentiful, but since this should appeal to high-school students, I think, the movie Inception (the one starring DiCaprio) could be used. In this movie, the `push` is when the characters enter a dream, and `pop` is when they wake up from the dream. Characters must wake up from their dreams in the exact reverse order from the one in which they entered them.
* Palindrome. I.e. the way to recognize one by `push`ing half of it on a stack and then `pop`ing the other half.

> **Comments:**
> **username_1**: Welcome to Computer Science Educators! Could you add some details on how the first two are an example of a stack?  
> **username_32**: @ItamarGreen OK.  
> **username_1**: The first example really is a **very** good one.  

---

### Answer by username_31 on 2017-06-19. Score: 3

In my view, a good computer science example for stack-oriented processing is the PostScript language. 
The Hello world example from the Wikipedia page shows the Reverse Polish (postfix) notation used in PostScript (similar to the CS50 AP Calc 2.0 username_27 showed in his answer that uses prefix notation):
%!PS
 /Courier             % name the desired font
 20 selectfont        % choose the size in points and establish 
                      % the font as the current one
 72 500 moveto        % position the current point at 
                      % coordinates 72, 500 (the origin is at the 
                      % lower-left corner of the page)
 (Hello world!) show  % stroke the text in parentheses
 showpage             % print all on the page

Input tokens would be pushed on a stack as they are parsed, and when an operator or command is encountered that needs n arguments, the upper n tokens would be popped from the stack, used for calculation or function execution and any result pushed on the stack again. 
This can even better be seen in the example that draws a line, using a conversion from PostScript points to millimeters:
/mm {360 mul 127 div} def
 0 0 moveto
 0 40 mm lineto stroke

The first line defines¹ a conversion function mm which is used in the third line to draw a vertical line 40 mm long. The function pops the top element from the stack, multiplies it with 360, divides it by 127 and pushes the result on the stack again.

¹ In fact, the def command, which defines a function, will not put its result back on the stack but into a dictionary which is used to look up commands.

> **Comments:**
> **username_8**: Welcome to cseducators! This is a very nice use-case. I hope we hear more from you in the future.  
> **username_28**: I note that postscript is built on a Forth language base. Forth itself is stack oriented.  

---

### Answer by username_7 on 2017-06-19. Score: 2

* In Australia at least, many supermarkets store shopping trolleys in a dead-end corral. So when you get a trolley for your shopping it will be the last one someone previously pushed into the corral.
* The paper into a photocopier tray
* For a Biblical reference: [Matthew 20:16](http://biblehub.com/matthew/20-16.htm)
* The way many of us process interruptions. We pause one task to focus on the interruption. We might pause that task to work on a subsequent interruption. Repeat for as many levels as you want. And then as each task is completed we return to the previous interrupt level.

> **Comments:**
> **username_8**: Welcome to CSE! Good example about processing interruptions.  But isn't Matthew 20:16 really more of an example of list reversal? ;-)  I hope we'll hear more from you in the future.  

---

### Answer by username_9 on 2017-06-20. Score: 2

The call stack
They've presumably already learned about functions, so if you use that as the example, you both teach them about stacks and give them a deeper understanding of how functions work.
I would take it in two main phases, using code similar to this as an example.
h(c) {
    print(c)
    return
}

g(b) {
    h(b + 3)
    print("foo")
    return
}

f(a) {
   x = 42
   g(x)
   h(x)
   print("bar")
   return
}

First, focus on how the return always knows to transfer control to the statement after the line the function was called on.  So for instance, the return from h might go to either g or f, depending on where it was called from, and in the former case, g in turn knows where it was called from.  If the language they're using is one that prints the call stack when it crashes, they're probably already somewhat familiar with this.  
Make sure they fully understand how the control flow works first, then bring in the concept of a stack and explain how you can implement function calls by storing the return addresses on the stack whenever you call a function, and popping them whenever you return.
Once they understand that, you might want to proceed to explain how parameters are stored on the stack.  That might confuse them a bit, though, since you can't access elements other than the one on top in a "theoretically pure" stack, but you do when accessing values in the stack frame. I would probably just mention to them that the reality is a bit more complicated than what you just described, but save the details for a later lesson.


---

### Answer by username_10 on 2017-06-20. Score: 2

A stack can be used to verify that an HTML document is well-formed. You begin with an empty stack.

When a tag opens (say

), the tag's type, in this case, "p", onto the stack.

When a tag is self-closing, do nothing.

When a tag closes, (say

), check to see that it matches the tag on the top of the stack by peeking at it. If there is a match, pop the stack. If there is a mismatch, emit an error message telling where the error lurks in the HTML file you are scanning.

If, at any time in the process you find an empty stack, report an error.

At the end:

If there are still tags on the stack, you have unclosed tags; report an error.

If the stack is empty, your HTML file has balanced tags.


---

### Answer by username_11 on 2017-06-19. Score: 2

I am not a computer science educator at all, but this question immediately reminded me of Leo Brodie's book *Starting Forth* from 1981 (!) with some cute [visualizations of stack manipulations](https://www.forth.com/starting-forth/1-forth-stacks-dictionary/#The_Stack_Forth8217s_Workspace_for_Arithmetic). This links up with @username_31's answer about *the PostScript language*.


---

### Answer by username_12 on 2018-11-19. Score: 1

A refrigerator: You put food in the freezer. To take out oldest food, first, you need to take out all newer food.


---

### Answer by username_13 on 2017-06-20. Score: 1

Packing a suitcase: the items last to be packed are the first to come out (assuming you place items directly on top of each other)

A couple of others:
-- A stack of papers
-- A stack of chairs

> **Comments:**
> **username_1**: This answer could really benefit from more explanation. Could you add some explanation to how those examples are a stack?  

---

### Answer by username_14 on 2021-04-24. Score: 1

History in your browser, recurrence in functions, "undo" like control-z in many programs are examples of stack usage


---

