1

i was trying to make a calculator in C. I wrote that code

#include <stdio.h>

int main()
{
    char proc;
    float x,y,z;
    printf("Enter the proccess you need to do :\nA) +\nB) -\nC) *\nD) /\n>>>  ");
    scanf("%c", &proc);
    if (proc !='A' || proc !='a' || proc !='B' || proc !='b' || proc !='C' || proc !='c' || proc !='D' || proc !='d' )
    {
            printf("enter a valid charecter.\n");
            return 0;
    }
    else 
    printf("Enter your first number: ");
    scanf("%f", &x);
    printf("Enter your seconde number: ");
    scanf("%f", &y);

    //Start of IF statment 
    if (proc =='A' || proc == 'a')
    {
            z = x+y;
            printf("The sum is %.2f:\n",z);
    }
    else if (proc =='B' || proc == 'b')
    {
            z = x-y;
            printf("The sum is %.2f:\n",z);
    }
    else if (proc =='B' || proc == 'b')
    {
            z = x*y;
            printf("The sum is %.2f:\n",z);
    }
    else if (proc =='B' || proc == 'b')
    {
            z = x/y;
            printf("The sum is %.2f:\n",z);
    }
    else   printf("Enter a valid charecter.\n");
            //End of IF statment
    return 0;
}

but when i try to run it and try for example A it show "enter a valid character." which i need it if i type non of these chars A,B,C,D also in lower case . Did i do it in a wrong way ?

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29

2 Answers2

3

Yes you thought about it incorrectly. Think about the logic:

proc !='A' || proc !='a' || ...

Take the example where you put in 'A'. Then you evaluate to:

false || true || ...

true || anything is always true, so you have a problem. You want &&.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
0

Although correct answer is in the comments already, Let me tell you the correct way of doing it.

First of all, you are checking many unnecessary conditions, you can simply do something like this:

// Check here about this function : https://stackoverflow.com/questions/2661766/c-convert-a-mixed-case-string-to-all-lower-case
proc = tolower(proc);

And then simply check for only 4 conditions, you are checking 4*2, 8 conditions

// Using '&&' here will solve your problem.
if(proc != 'a' && proc != 'b' && proc != 'c' && proc != 'd')

This whole program can also be drilled down if you can learn switch case.

  • 1
    There is no single "correct way" in programming. A particular problem can be solved in many ways. The best solution depends on your priorities. Writing shorter code isn't always the "correct/best way". BTW: Your code could be even shorter: `if (proc < 'a' || proc > 'd')` – Support Ukraine Nov 05 '17 at 07:25