diff --git a/README.md b/README.md index 6a05f063..af170ef7 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ This repository contains examples of various algorithms written on different pro | Data Structure | C | CPP | Java | Python | |:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:| | [Queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) | | [:octocat:](queue/Cpp) | | | -| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | [:octocat:](stack/Python) | +| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) |[:octocat:](stack/C )| | [:octocat:](stack/Java) | [:octocat:](stack/Python) | | [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | | | [:octocat:](linked_list/Python) | | [AVL Tree](https://en.wikipedia.org/wiki/AVL_tree) | [:octocat:](avl_tree/C) | | [:octocat:](avl_tree/Java) | [:octocat:](avl_tree/Python) | diff --git a/stack/C/stackUsingArray.c b/stack/C/stackUsingArray.c new file mode 100644 index 00000000..ade7034a --- /dev/null +++ b/stack/C/stackUsingArray.c @@ -0,0 +1,39 @@ +#include +#include + +/*Using variable i to push elements then pop and print the elements. */ + +int main() { + void push(int *arr, int *top, int n, int i); + int pop(int *arr, int *top); + // number of elements + int n = 6; + int arr[n], top = -1; + // push all elements into the stack + for(int i = 0; i < n; i++) { + push(arr, &top, n, i); + } + printf("\n"); + // pop elements one by one. + for(int i = 0; i < n; i++) { + printf("%d ", pop(arr, &top)); + } +} + +void push(int *arr, int *top, int n, int i) { + if(*top == n) { + printf("\nStack is full. \n"); + } else { + arr[++(*top)] = i; + } +} + +int pop(int *arr, int *top) { + if(*top == -1) { + printf("\n Stack empty!\n"); + exit(1); + } else { + return(arr[(*top)--]); + } + return 0; +}