Home > OS >  Else If statement in C is not executing correctly
Else If statement in C is not executing correctly

Time:10-11

I wrote a C program for a calculator using else...if statement. There are no syntax errors and it compiles well but the program skips all the conditions and and only executes the last one (displaying the error message). I can't figure out what is wrong. here is my code. I'm sorry this if this is a stupid question, i tried googling this but came up with nothing.

code:

#include<stdio.h>
{
float no1, no2, ans;
char op;

printf("ENTER 1ST NUMBER:\n");
scanf("%f",&no1);
printf("ENTER 2ND NUMBER:\n");
scanf("%f",&no2);
printf("ENTER A BASIC MATHEMATICAL OPERATOR:\n");
scanf("%ch",&op);

if(op==' ')
{
    ans=no1 no2;
}else if(op=='-')
{
    ans=no1-no2;
}else if(op=='*')
{
    ans=no1*no2;
}else if(op=='/')
{
    ans=no1/no2;
}else
{
    printf("INVALID OPERATOR!!\n");
}

printf("ANSWER=%.2f\n", ans);

return 0;
}

Update: thank you for helping! And i will be mindful to copypaste the code instead of posing screenshots in the future,

CodePudding user response:

I think your issue is similar to this one Issues with using if/else statements correctly in C language

Changing scanf("%ch",&op); to scanf("%c", &op); might solve your problem.

CodePudding user response:

Your code looks good, but if you don't copy the code we can not debug to search the error. I recommend you to debug the code and control what value have the op variable before the if else.

If you copy the code i can try to debug and search the error.

  • Related