Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Created June 4, 2020 13:03
Show Gist options
  • Save voidnerd/784a286a2af29cc4f18200045dd18d44 to your computer and use it in GitHub Desktop.
Save voidnerd/784a286a2af29cc4f18200045dd18d44 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int main(void)
{
int num1 = -1, num2 = -1;
int result;
char key;
printf("Enter two numbers: ");
scanf("%d,%d", &num1, &num2);
/** Validate input */
if(num1 < 0 || num2 < 0)
{
printf("Error: enter positive two numbers only, eg. 3,4 \n");
return 1;
}
printf("Enter an operator: ");
/**
* the space before %c will help you to eat up \n char left over by first scanf
*/
scanf(" %c", &key);
switch(key)
{
case '*':
result = num1 * num2;
printf("%d %c %d = %d \n", num1, key, num2, result);
break;
case '-':
result = num1 - num2;
printf("%d %c %d = %d \n", num1, key, num2, result);
break;
case '+':
result = num1 + num2;
printf("%d %c %d = %d \n", num1, key, num2, result);
break;
case '/':
result = num1 / num2;
printf("%d %c %d = %d \n", num1, key, num2, result);
break;
default:
printf("Invalid Operator. use one of *, +, - or / \n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment