Home > Software design >  "else" block is executed every time even after the "if" statement is true
"else" block is executed every time even after the "if" statement is true

Time:05-25

In the delete function, the else part is executed every time even after the if statement is true. How can I solve that problem?

#include<stdio.h>
#include<stdlib.h>
#define MAX 10
int front=-1,rear=-1;
int Q[MAX];
void insert();
void delete();
void display();
void peek();

int main(){
int n;
while(1){
    printf("Enter your operation:-\n1.Insert\n2.Delete\n3.Peek\n4.Display\n5.Exit\n");
    scanf("%d",&n);
     switch(n){
        case 1:
        insert();
        break;
        case 2: 
        delete();
        break;
        case 3: 
        peek();
        break;
        case 4: 
        display();
        break;
        case 5: 
        exit(0);
    }
    }

return 0;
}

void insert(){
    int i;
    printf("Enter your number:\n");
    scanf("%d",&i);
    if(rear==MAX-1)
        printf("The queue is overflow");
        else if(front==-1 && rear==-1)
            front=rear=0;
        else
        rear  ;
        Q[rear]=i;  
    }
void delete(){
    int v;
    if(front==-1 || front>rear)
    printf("Queue is underflow\n");
    else
    v=Q[front];
    front  ;
    printf("Your deleted number is:%d\n",v);

}
void peek(){
    if(front==-1 || front>rear)
    printf("Queue is underflow\n");
    else
    printf("The first number is:%d\n",Q[front]);
}
void display(){
    int i;
    if(front==-1 || front>rear)
     printf("Queue is underflow\n");
     else
     printf("Your created Queue is:\n");
     for(i=front;i<=rear;i  ){
         printf("]\n",Q[i]);
     }
}`

CodePudding user response:

You need to use a compound statement as for example

else
{
    v=Q[front];
    front  ;
    printf("Your deleted number is:%d\n",v);
}

Other wise this code snippet

else
v=Q[front];
front  ;
printf("Your deleted number is:%d\n",v);

is equivalent to

else
{
    v=Q[front];
}
front  ;
printf("Your deleted number is:%d\n",v);

Pay attention to that for example the function insert as is has a bug

void insert(){
    int i;
    printf("Enter your number:\n");
    scanf("%d",&i);
    if(rear==MAX-1)
        printf("The queue is overflow");
    else if(front==-1 && rear==-1)
        front=rear=0;
    else
        rear  ;
    Q[rear]=i;  
}

It seems you mean

void insert(){
    if(rear==MAX-1)
    { 
        printf("The queue is overflow");
    }
    else
    {
        int i;
        printf("Enter your number:\n");
        scanf("%d",&i);
        if( front==-1 )
            front = 0;
        else
            rear  ;
        
        Q[rear]=i;  
    }
}

Usually one of reasons of bugs is a bad formatting of the code.

  • Related