This is a code for queue. my array size is 5 but I am able to insert more than 5 element and also can print all of them. how it is working?
#include <iostream>
#include <stdlib.h>
using namespace std;
int front=0, rear=-1;
int queue_array[5];
void enqueue(int a){
if(front>4){
cout<< "queue overflow" << endl;
return;
}
rear++;
queue_array[rear] = a;
cout << "Inserted" << a << endl;
}
void dequeue(){
if(front > rear){
cout << "queue underflow" << endl;
return;
}
int temp = queue_array[front];
for(int i=1;i<=rear;i++){
queue_array[i-1] = queue_array[i];
}
rear--;
cout << "popped: " << temp << endl;
}
void display(){
if(front>rear) cout << "Queue empty" << endl;
for(int i=0; i<=rear; i++){
cout << queue_array[i] << " " ;
}
}
int main(){
int element;
while(1){
cout << "\n1.Enqueue \n2.Dequeue\n3.Display \n4. Exit \n Enter your choice: ";
cin >> element;
switch(element){
case 1: cin >> element;
enqueue(element);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
}
}
return 0;
}
Also queue all operation is working fine. What is the reason for that? Thanks in advance.