/* 1a) Write a C program that implement Stack using Array*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
int stack[MAX_SIZE],top=-1;
// Function to add an item to the stack
void push(int item) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = item;
}
}
// Function to remove an item from the stack
int pop() {
if (top==-1) {
printf("Stack Underflow\n");
return -1; // Indicating underflow
} else {
return stack[top--];
}
}
// Function to get the top item of the stack
int peek() {
if (top==-1) {
printf("Stack is Empty\n");
return -1; // Indicating empty stack
} else {
return stack[top];
}
}
// Function to Display all the items from stack
void display()
{
int i;
if (top==-1)
printf("Stack is Empty\n");
else{
for(i=top;i>-1;i--)
printf("%d\n",stack[i]);
}
}
// Main function
int main()
{
int ch,data;
do
{
printf(“STACK OPEARTIONS\n”)
printf("\n1. Push\n2. Pop\n3. Peek(top)\n4. display\n5. Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter data to push:");
scanf("%d",&data);
push(data);
break;
case 2: printf("Popped: %d\n", pop());
break;
case 3: printf("Top element: %d\n", peek());
break;
case 4: display();
break;
case 5: break;
default: printf("Enter valid choice");
}
} while(ch!=5);
return 0;
}
/* 1b) Write a C program that implement Queue using Array*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
int queue[MAX_SIZE],front=-1, rear=-1;
// Function to add an element to the queue
void enqueue(int element)
{
if (rear == MAX_SIZE - 1)
{
printf("Queue Overflow\n");
}
else
{
if(front == -1)
front = 0;
queue[++rear] = element;
}
}
// Function to remove an element from the queue
int dequeue()
{
int item;
if (front == -1)
{
printf("Queue Underflow\n");
return -1; // Indicating underflow
}
else
{
int item = queue[front++];
if (front > rear) // Queue is now empty
{
front = -1;
rear = -1;
}
return item;
}
}
// Function to display all the items from Queue
void display()
{
int i;
if (front == -1)
{
printf("Queue is Empty\n");
}
else
{
for(i=front;i<=rear;i++)
printf("%d\t",queue[i]);
}
}
// Main function
int main() {
int ch,data;
do{
printf("\n QUEUE OPERATIONS\n");
printf("\n1. Insert\n2. Delete\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter data to insert: ");
scanf("%d",&data);
enqueue(data);
break;
case 2: printf("Deleted: %d\n", dequeue());
break;
case 3: display();
break;
case 4: break;
default: printf("your choice is wrong!..");
}
}while(ch!=4);
return 0;
}