C Programming: Stack Push Function
In the C language, we typically use arrays to simulate stack operations, with the push function used to add elements to the stack. Here is a simple example demonstrating the use of the push function.
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int element) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = element;
printf("%d pushed to stack\n", element);
}
}
int main() {
push(10);
push(20);
push(30);
return 0;
}
In the example above, we defined an array called stack to simulate a stack, with the top variable used to keep track of the top position. The push function takes an integer parameter element and adds it to the stack. In the main function, we called the push function three times, adding 10, 20, and 30 to the stack in order. When the stack is full, the push function will output a “Stack Overflow” prompt.
I hope this example can help you understand how to use the push function in C language.