I was trying to make a queue program on my own, but when I enqueue an element and then display the queue, I find an extra element already lying around in my queue. Also, I am not able to add the number of elements as I decided from the size of the queue because of the garbage numbers eating up space in my queue. Here's the code for it :
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
void enqueue();
void dequeue();
void display();
int main(){
int size;
printf("Enter the size of the queue : ");
scanf("%d", &size);
int choice, element;
int queue[size];
int front = 0;
int rear = 0;
while(true){
printf("Queue Operations\nPress 1 for Enqueue\nPress 2 for Dequeue\nPress 3 for Display\nPress 4 for exit\n");
scanf("%d", &choice);
switch(choice){
case 1:{
if(rear == size - 1){
printf("Overflow!\n");
}
else{
printf("Enter the element you want to enqueue : ");
scanf("%d", &element);
queue[rear] = element;
rear ++;
}
break;
}
case 2:{
if(front == rear){
printf("Underflow!\n");
}
else{
printf("The element deleted is %d\n", queue[front]);
front += 1;
size+=1;
}
break;
}
case 3:{
if(front == rear){
printf("Queue is empty.\n");
}
else{
for(int i = front; i <= rear; i ++){
printf("%d ", queue[i]);
}
printf("\n");
}
break;
}
case 4:{
exit(0);
}
default:{
printf("Invalid Choice.\nTry again.\n");
break;
}
}
}
return 0;
}