C Program to Enter an Operator and Two Operands and Perform the Operation

In this program, the user is asked to enter any one of the operators +, -, *, / and also two operands. The operation chosen by the user is carried out on the two operands.

#include<stdio.h>

int main()

{

  int a,b,res;
  char c;
  printf ("Enter any one operator +, -, *, / n");
  scanf("%c", &c);
  printf ("n Enter two numbers n");
  scanf ("n %d n %d",&a, &b);
  switch(c)
  {
    case '+': res=a+b;
    printf("n The sum is %d",res);
    break;

    case '-': res=a-b;
    printf("n The difference is %d",res);
    break;

    case '*': res=a*b;
    printf("n The product is %d",res);
    break;

    case '/': res=a/b;
    printf("n The quotient is %d",res);
    break;

    default: printf ("n Invalid entry");
  }

  return 0;
}

Here, the operator given by user is stored in variable c and the two operands are stored in variable a and b. The operator in variable c is checked against a list of labels in the switch statement. When a matching label is found, the list of operations associated with the label is executed meaning that if the variable c is equal to ‘+’ sign then the operations res=a+b and the statement “The sum is …“ is executed and the rest of the operations inside the switch statement is skipped. If the user enters other characters than +, -, *, / then “Invalid Entry” is displayed.

The program can also be written by using else if statement as:

#include<stdio.h>

int main()

{

  int a, b, res;
  char c;
  printf ("Enter any one operator +, -, *, / n");
  scanf("%c", &c);
  printf ("n Enter two numbers n");
  scanf ("n %d n %d",&a, &b);

  if (c=='+')
  {   
    res=a+b;
    printf("n The sum is %d",res);
  }

  else if(c== '-')
  {
    res=a-b;
    printf("n The difference is %d",res);
  }

  else if(c== '*')
  {
    res=a*b;
    printf("n The product is %d",res);
  }

  else if(c==’/’)
  {
    res=a/b;
    printf("n The quotient is %d",res);
  }

  else
  {
    printf ("n Invalid entry");
  }

  return 0;

}

Here, the character in variable c is check against the if condition and the else if conditions. When the condition that matches with the character in variable c is found, the statements associated with that variables is executed. If no matching condition is found then “Invalid Entry” is displayed.

Output:

Enter any one operator +, -, *, /

+

Enter two numbers

5

3

The sum is 8

Enter any one operator +, -, *, /

/

Enter two numbers

100

20

The quotient is 5