EXPERIMENT 3_ds

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

EXPERIMENT 3

AIM 1: Write a program for stack that performs following operations using array. (a) PUSH (b) POP (c) PEEP (d)
CHANGE (e) DISPLAY

Code:

#include <stdio.h>

#define MAX 5 // Maximum size of the stack

int stack[MAX];

int top = -1; // Indicates the top position in the stack

// Function to push an element onto the stack

void push(int value) {

if (top == MAX - 1) {

printf("Stack overflow! Cannot push %d.\n", value);

} else {

top++;

stack[top] = value;

printf("%d pushed onto the stack.\n", value);

// Function to pop an element from the stack

void pop() {

if (top == -1) {

printf("Stack underflow! Cannot pop.\n");

} else {

printf("%d popped from the stack.\n", stack[top]);

top--;

// Function to peep (view the top element)

void peep() {
if (top == -1) {

printf("Stack is empty! Nothing to peep.\n");

} else {

printf("Top element is %d.\n", stack[top]);

// Function to change the value of a specific position in the stack

void change(int position, int value) {

if (position < 1 || position > top + 1) {

printf("Invalid position! Position should be between 1 and %d.\n", top + 1);

} else {

stack[position - 1] = value;

printf("Value at position %d changed to %d.\n", position, value);

// Function to display all elements in the stack

void display() {

if (top == -1) {

printf("Stack is empty! Nothing to display.\n");

} else {

printf("Stack elements are:\n");

for (int i = top; i >= 0; i--) {

printf("%d\n", stack[i]);

int main() {

printf("\nAjeet Sahni\n");

printf("\n0801EI221009\n");

int choice, value, position;


while (1) {

printf("\nSTACK OPERATIONS:\n");

printf("1. PUSH\n2. POP\n3. PEEP\n4. CHANGE\n5. DISPLAY\n6. EXIT\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to push: ");

scanf("%d", &value);

push(value);

break;

case 2:

pop();

break;

case 3:

peep();

break;

case 4:

printf("Enter position to change: ");

scanf("%d", &position);

printf("Enter new value: ");

scanf("%d", &value);

change(position, value);

break;

case 5:

display();

break;

case 6:

printf("Exiting...\n");

return 0;

default:

printf("Invalid choice! Please enter a number between 1 and 6.\n");

}
}

return 0;

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy