Answer to Question #239604 in C for Rohan

Question #239604

A system has a 16 byte memory. Therefore it can hold only 8 integers. Initially the

memory is empty. It can perform four operations. They are

1. Push

2. Pop

3. Enqueue and

4. Dequeue

Here Push, Pop operations maintain the rules of a simple stack and Enqueue, Dequeue

operations maintains the rules of a simple queue. If the memory is full then the system discards

any push or enqueue operation and if the memory is empty then it discards pop

and dequeue operations. Now write a program using the concept of stack and queue to

simulate the system.

Input: Test case will start with an input n that contains the numbers of operations. Next n

line will have the operations. Specifications of operations are given below:

E x : Enqueue x // here x is an interger number

D : Dequeue

P x : Push x

O : Pop

Output: Output the final memory status of the system. If the memory is empty print a

message “Memory is Empty”.

Sample input :

12

D

P 7

P 9

E 13

P 17

D

E 19

D

P 23

O

O

E 18

Sample output:

13 17 18


1
Expert's answer
2021-09-20T11:09:21-0400
#include<stdio.h>
int arr[8]; //memory can only carry 8 integers
int rear = -1, front = -1, top = -1 ,size_of_array = 8;
void push(int data) {
   if(top>=size_of_array-1)
   printf("Memory is full");
   else {
      top++;
      rear++;
      arr[top]=data;
   }
}
void pop() {
   if(top<=-1)
   printf("Memory is empty");
   else {
     front++;
      top--;
   }
}


void Enqueue(int data) {
  
   if (rear == size_of_array - 1)
   printf("Memory is full");
   else {
      if (front == - 1)
      front = 0;
     
      rear++;
      top++;
      arr[rear] = data;
   }
}
void Dequeue() {
   if (front == - 1 || front > rear) {
      
      return ;
   } else {
      
      front++;
      top--;
   }
}
void display(){
	if(top<=-1){
		printf("Memory is Empty\n");
	}
	else{
		int i;
		for(i=0; i<top; i++){
			printf("%d   ", arr[i]);
		}
	}
	
}
int main(){
	int n;
	printf("Enter the number of operations\n");
	scanf("%d", &n);
	int i=0;
	while(i<n*2){
		char c;
		scanf("%c", &c);
		if(c=='D'){
			Dequeue();
		}
		else if(c=='P'){
			int data;
			scanf("%d", &data);
			push(data);
		}
		else if(c=='E'){
			int data;
			scanf("%d", &data);
			Enqueue(data);
		}
		else if(c=='O'){
			pop();
		}
		
		
		i++;
	}
	display();
	
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS