whats the problem with this program

+3 votes
asked Nov 19 by Sai pavan (150 points)
#include <stdio.h>

int main()
    char no1=15,no2=5;
    char opr;
        case '+':printf("%d",no1+no2);break;
        case '-':printf("%d",no1-no2);break;
        case '*':printf("%d",no1*no2);break;
        case '/':printf("%d",no1/no2);break;
        return 0;


1 Answer

+1 vote
answered 6 days ago by Peter Minarik (12,220 points)

Code does not compile?

If your code does not compile, make sure you've selected the right programming language in the top right corner. (This code can be compiled as a C or C++ code -- with various C++ standards.)

Would you like to improve your code?

To me it looks like the program does the basic functionality. So if your question is how to improve it?

Here are a few tips:

  • reading characters is a tricky thing with scanf as it could read content from the last input. So it makes sense to tell it to ignore whitespace coming in from the standard input. You do that by adding an extra space before the format specifier: scanf(" %c").
  • You can try to allow the user to enter the inputs (no1, no2) and not to be fixed numbers
  • With the above improvement you open up a hell of new problems :) You need to think about how your code can be broken by various user inputs.
    • Invalid input
      • The user may not enter a valid number (e.g. "one" is invalid, not a number). You have to validate the user input if it's really a number
      • The user may enter floating point numbers, not integral numbers
      • The number entered may not fit to the storage (char). You can increase it to int or long it, but the user can always just enter 99999999999999999999999999999999999 :)
      • So you need to deal with all kind of invalid inputs
    • The number after the operation may not fit into the storage. E.g. char ranges from -128 to 127. If the user enters 120 and 100 the sum is more than 127 and you'll be in trouble. You need to deal with this. (e.g. tell the user that the sum would not fit into the selected storage). Also, I'd suggest using int at least or long int, not char.
    • You need to deal with zero division (e.g. no2 = 0 --> no1 / 0 causes a runtime error)
  • You could make your code more user friendly and tell the user what the program is expecting him/her to do (e.g.: "The program will ask for two numbers then an operation to be executed on them." Then ask the user to enter the numbers and the operation one-by-one.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.