Hello C# 005

"Sometimes it is the people no one can imagine anything of who do the things no one can imagine." – Alan Turing (maybe)

Stack

You can write code that is executed conditionally or repeat, so you may consider yourself a programmer now!
Unfortunately coding only with whiles and ifs is not feasible and other very smart people discovered a lot of others structures that we use on our day to day coding.

Instead of jumping right into the syntax and logical structures, we are going to discover them using our whiles and ifs! And the stack is the first one.

The stack is a Data Structure (way of organizing data) that offer two actions: push and pop. Pushing adds an element to the stack and popping removes in the reverse order of pushes (aka LIFO).

Structure

// this is not code, it is just an annotation
Stack {
count, // The amount of elements in the stack
elements[] // The elements itself
}

As you will later learn, there may be multiple ways to implement a given data structure but the structure above fits our context.
Consider X an index in of our memory array where our stack is located, m[X] contains the count, m[X+1] the first element and so on.

Using it

Here is an example of pushing and popping something from the stack:

> var m = new int[128];
> m[10] = 0; // stack at X=10
> // Pushing 42 to the stack
> m[10] = m[10] + 1;
> m[10+m[10]] = 42;
> // Reading the last element in the stack
> m[10 + m[10]]
> // Popping the last element from the stack
> m[10] = m[10] - 1;

We can now reason about the stack in terms of pushes and pops that can be transformed into code using the example above.

// not code, but you can write code that does the following:
> new stack at X=20;
> push 42 to stack;
> if(last in stack > 40)
push 30;
else
push 20;
> m[0] = (last in stack) * 3;
> pop;
> push m[0] to stack;

[Try by yourself] What are the elements in the stack at the end of the "not code" example?

[Try by yourself] Convert the "not code" example to proper code.

[Try by yourself] The reference code for popping handles badly the case of m[X] == 0. Do you see why? Can you improve it?

Up Next

`Strings` and our first problem to solve.


Go home.

☆Powered by Azure Blob