Why does my scanf act before my printf does?
In this code, when asking for an element to insert, the cursor asks me to enter one more value which later on I realised was the choice input. Why is it asking it before the printing of choice? And there may be some error under the main().
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int q[MAX];
int front = 0;
int rear = -1;
int item;
void insert()
{
if(rear == MAX-1)
{
printf("Queue Overflow\n");
return;
}
rear = rear + 1;
q[rear] = item;
}
int delete()
{
if(front>rear)
{
printf("Queue Underflow\n");
return;
}
front = front + 1;
int itemdeleted = q[front];
}
void display()
{
if(front>rear)
{
printf("Queue Underflow \n");
return;
}
for(int i=front; i<=rear; i++)
{
printf("%d\n", q[i]);
}
printf("\n");
}
int main()
{
while(1)
{
int choice, itemdeleted;
printf("Enter your choice\n");
printf("Choose\n 1. Insert\n 2. Delete\n 3. Display\n 4. Exit\n");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("Enter items to insert\n");
scanf("%d\n", &item);
insert();
break;
case 2: delete();
printf("The deleted item is %d\n", itemdeleted);
break;
case 3: display();
break;
case 4: exit(0);
break;
}
}
}
This is the output I am getting:
Enter your choice
Choose
1. Insert
2. Delete
3. Display
4. Exit
1
Enter items to insert
1
3
Enter your choice
Choose
1. Insert
2. Delete
3. Display
4. Exit
1
Enter your choice
Choose
1. Insert
2. Delete
3. Display
4. Exit
1
Enter items to insert
5
3
Enter your choice
Choose
1. Insert
2. Delete
3. Display
4. Exit
1
5
Enter your choice
Choose
1. Insert
2. Delete
3. Display
4. Exit