Skip to content
TheChatArchiveThe Chat Archive
Human-written demonstration (OpenAssistant volunteers)· OpenAssistant (human-written)Hugging Face OpenAssistant Conversations (oasst2)

Can you write a program in C to implement a stack data structure?

In OpenAssistant data, “assistant” turns were written by human volunteers as demonstrations. They are not model outputs.
  1. User

    Can you write a program in C to implement a stack data structure?

  2. Assistant

    Sure, here's a simple implementation of a stack data structure in C. This program uses an array to implement the stack and includes functions for pushing, popping, and displaying elements of the stack.

    #include <stdio.h> #define MAX 10 // Defining maximum size of stack

    int stack[MAX], top = -1;

    // Function to add an element to the stack void push(int val) { if(top == MAX-1) printf("\nStack is full"); else { top++; stack[top] = val; } }

    // Function to remove an element from the stack int pop() { if(top == -1) { printf("\nStack is empty"); return -1; } else { return stack[top--]; } }

    // Function to display elements of the stack void display() { if(top == -1) printf("\nStack is empty"); else { for(int i = top; i >= 0; i--) printf("\n%d", stack[i]); } }

    int main() { int choice, val; do { printf("\nMENU"); printf("\n1. Push"); printf("\n2. Pop"); printf("\n3. Display"); printf("\n4. Exit"); printf("\nEnter your choice: "); scanf("%d", &choice); switch(choice) { case 1: printf("\nEnter the number to be pushed on stack: "); scanf("%d", &val); push(val); break; case 2: val = pop(); if(val != -1) printf("\nThe value deleted from stack is: %d", val); break; case 3: display(); break; } } while(choice != 4); return 0; }

    In this program, the push function is used to add an element to the stack, the pop function is used to remove an element from the stack, and the display function is used to display the elements of the stack. The main function provides a menu for the user to choose an operation.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.