{"id":61,"date":"2022-01-19T14:58:09","date_gmt":"2022-01-19T14:58:09","guid":{"rendered":"https:\/\/noerguerra.com\/?p=61"},"modified":"2022-01-20T07:35:22","modified_gmt":"2022-01-20T07:35:22","slug":"creating-a-stack-in-c-using-arrays","status":"publish","type":"post","link":"https:\/\/noerguerra.com\/blog\/creating-a-stack-in-c-using-arrays\/","title":{"rendered":"Creating a stack in C using arrays"},"content":{"rendered":"<h2>What is a Stack in programming?<\/h2>\n<p><a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/01\/image-000.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/01\/image-000.png\" alt=\"\" \/><\/a><br \/>\nA stack is a linear data structure that allows to access and store values in order LIFO (Last In First Out) or FILO (First In Last Out).<br \/>\nThe way this structure behaves in programming is similar to that of a stack of objects in the real world, for example, a stack of plates or stones, as you can see in the following figure:<\/p>\n<p><a href=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/01\/image-002.png\"><img decoding=\"async\" src=\"https:\/\/noerguerra.com\/wp-content\/uploads\/2022\/01\/image-002.png\" alt=\"\" \/><\/a><\/p>\n<p>A stack has at least three basic operations, all of them with a complexity of O(1):<\/p>\n<ul>\n<li>PUSH<\/li>\n<li>POP<\/li>\n<li>PEEK<\/li>\n<\/ul>\n<p>Some other operations usually accompany these:<\/p>\n<ul>\n<li>Check if the stack is empty<\/li>\n<li>Initialize the stack<\/li>\n<li>Show (or print) the stack<\/li>\n<li>Search a value in the stack<\/li>\n<li>Get the size of the stack<\/li>\n<\/ul>\n<p>Some examples of stacks in software are undo\/redo operations that you can find in many programs or syntax highlighting in text editors, among others.<\/p>\n<h2>How to code a stack in C<\/h2>\n<p>There are several ways you can program a stack in C, the most common being by using arrays and linked lists. In this  article, I will show you how to do it using arrays, while in the second part, I will show you how to create a C stack using  linked lists.<br \/>\nThe structure of a stack in the C language is the following:<\/p>\n<pre><code>struct Stack{\nint top;\nint capacity;\nint* array;\n};<\/code><\/pre>\n<p>We will add some other auxiliary functions to this structure to instantiate it and check when it is full\/empty.<\/p>\n<pre><code>struct Stack* createStack(int capacity){\nstruct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); \/\/Reserve memory block\nstack->capacity = capacity; \/\/Assign the size of the stack\nstack->top = -1; \/\/ Initialize the value at the top of the stack\nstack->array = (int*)malloc(stack->capacity*sizeof(int)); \/\/Define an array that will store the data\nreturn stack;\n}\n\nint isFull(struct Stack* stack){\nreturn stack->top == stack->capacity-1;\n}\n\nint isEmpty (struct Stack* stack){\nreturn stack->top == -1;\n}<\/code><\/pre>\n<p>Next, we will define the stack\u2019s main functions, which will allow us to add and remove elements to it.<\/p>\n<h2>Basic Stack Operations<\/h2>\n<h3>PUSH<\/h3>\n<p>As shown in the figure at the beginning of the article, the PUSH function consists of placing an element at the top of the stack.<br \/>\nWe can perform this operation by placing the value received by the function at the end of the array.<\/p>\n<pre><code>void PUSH(struct Stack* stack, int element){\nif (isFull(stack))\n    return;\nstack->array[++stack->top] = element;\n}<\/code><\/pre>\n<h3>POP<\/h3>\n<p>To implement the unstacking function, or POP, we only need to do the opposite of the PUSH function. That is, subtracting 1 to the stack stop and return the value of the popped element.<\/p>\n<pre><code>int POP(struct Stack* stack){\nif (isEmpty(stack))\n    return INT_MIN;\nreturn stack->array[stack->top--];\n}<\/code><\/pre>\n<h3>PEEK<\/h3>\n<p>The PEEK function allows us to know which element is at the top of the stack. We can easily implement it by unstacking the top of the stack and storing its value in a variable, restacking the element immediately afterward, and returning the stored value:<\/p>\n<pre><code>int PEEK(struct Stack* stack){\nint val = POP(stack);\nPUSH(stack, val);\nreturn val;\n}<\/code><\/pre>\n<h2>Additional Stack Operations<\/h2>\n<p>After implementing PUSH(), POP() and PEEK(), and the corresponding functions to know the state of the stack (full or empty) and the necessary functions to create new stacks, we still have to implement the following functions:<\/p>\n<ul>\n<li>Print the content of the stack<\/li>\n<li>Search for a value within the stack<\/li>\n<li>\n<p>See the size of the stack<br \/>\nTo print the stack\u2019s contents, we have to go through the array that makes up the stack and print the value stored in each index. Finding a value within the stack follows the same principle but we have to return the current index when the searched value is found.<br \/>\nReturning the stored value of the \u201ctop\u201d variable is enough to know the stack\u2019s size.<\/p>\n<pre><code>void print(struct Stack* stack){<\/code><\/pre>\n<p>for (int i = 0; i &lt;= stack-&gt;top; i++)<br \/>\nprintf(&quot;%i\\n&quot;, stack-&gt;array[i]);<br \/>\n}<br \/>\nint search(struct Stack<em> stack, int value){<br \/>\nfor (int i = 0; i &lt;= stack-&gt;top; i++)<br \/>\nif (stack-&gt;array[i] == value)<br \/>\nreturn i;<br \/>\nreturn -1;<br \/>\n}<br \/>\nint numElements(struct Stack<\/em> stack){<br \/>\nreturn stack-&gt;top+1;<br \/>\n}<\/p>\n<\/li>\n<\/ul>\n<p>Here is an example of the use of the implemented functions:<\/p>\n<pre><code>int main(){\nstruct Stack* stack = createStack(5); \/\/\/\/Create the stack with 5 slots\nPUSH(stack, 100); \/\/ [100,-,-,-,-]\nPUSH(stack, 200); \/\/ [100, 200, -,-,-]\nPUSH(stack, 300); \/\/ [100, 200, 300, ,- ,-]\nPUSH(stack, 400); \/\/ [100, 200, 300, 400, -]\nPUSH(stack, 500); \/\/ [100, 200, 300, 400, 500]\nPOP(stack); \/\/ [100, 200, 300, 400,-]\nPOP(stack); \/\/ [100, 200, 300, -, -]\nPUSH(stack, 600); \/\/ [100, 200, 300, 600]\nPUSH(stack, 700) \/\/ [100, 200, 300, 600, 700]\nprint(stack);\nprintf(\"The stack has %i elementos\\n\",numElements(stack));\nif (isFull(stack))\n    printf(\"The stack is full\");\n}<\/code><\/pre>\n<p>Using arrays is a simple way to create a stack in C and implement this data structure in this language. However, it has some disadvantages compared to creating a stack using a linked list, being one of them its defined size. In the next part of this article, I will show you how to create a stack and its basic operations using pointers and linked nodes.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is a Stack in programming? A stack is a linear data structure that allows to access and store values in order LIFO (Last In First Out) or FILO (First In Last Out). The way this structure behaves in programming is similar to that of a stack of objects in the real world, for example,&hellip; <a class=\"more-link\" href=\"https:\/\/noerguerra.com\/blog\/creating-a-stack-in-c-using-arrays\/\">Continue reading <span class=\"screen-reader-text\">Creating a stack in C using arrays<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":64,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[6],"tags":[],"class_list":["post-61","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-language","entry"],"_links":{"self":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts\/61","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/comments?post=61"}],"version-history":[{"count":4,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts\/61\/revisions"}],"predecessor-version":[{"id":70,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/posts\/61\/revisions\/70"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/media\/64"}],"wp:attachment":[{"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/media?parent=61"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/categories?post=61"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/noerguerra.com\/blog\/wp-json\/wp\/v2\/tags?post=61"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}