Hi guys welcome to my new blog. If you want to make a calculator using c programming then you are at the right place. In this blog i am going to tell that how to make a calculator using c programming & also going to discuss concepts used in it.
Pseudocode & concept:-
If you want to make code of a calculator or something big you should first right the pseudocode in order to solve the whole problem. This is how you should approach it:-
Declare variables float a,b,c,d & char x for operator sign
⬇️
Enter the first number
⬇️
Scan it
⬇️
Enter the second number
⬇️
Scan it
⬇️
Enter the operation +,-,÷,×
⬇️
Scan it
⬇️
Now,use switch case as there is one variable x(Operator +,-,÷,×)& multiple cases
⬇️
Case'+':For addition
⬇️
Case'-':For subraction
⬇️
Case'×':For multipication
⬇️
Case'/':For division
⬇️
Default:For invalid operator*
Switch case statements:-
Switch case statements are used in case of if elseif statements & when the cases depend on the variable inside switch if you enter 1 then case 1 will run. If 2 then case 2 and so on and after the whole case statement there is a break to get the control outside the loop. And there is a default statement there if someone enters different thing which is not mentioned in above case label then default statement will execute.
Syntax:-
switch(x)//x must be a variable
case 1: Statement 1;
break;
case 2: Statement 2;
break;
:
:
:
:
case n: Statement n;
break;
default: Statement def;
break;
Code for the calculator:-
#include< stdio.h >
#include< stdlib.h >
int main()
{
char y;
float a,b,c,d;//makes calculator more precise
printf("Enter the first number\n");
scanf("%f",&a);
printf("Enter the second number\n");
scanf("%f",&b);
printf("Enter the operation:\n+\n-\n*\n/\n");
scanf(" %c",&y);// Space before %c to have enter and then scan the character otherwise it will take enter as char & default case will run
switch(y)
{
case '+': c=a+b; //Case label 1
printf("ADDITION of two numbers is %f",c);
break;
case '-': c=a-b;
printf("SUBTRACTION of two numbers is %f ",c);
break;
case '*': c=a*b;
printf("MUTIPICATION of two numbers is %f",c);
break;
case '/': d=a/b;
printf("DIVISON of two numbers is %f ",d);
break;
default:
printf("Invalid operator");
break;
}
return 0;
}
I hope you liked the blog. Make sure that you comment on this blog & suggest things to make the calculator more better.Happy coding❤❤
Top comments (4)
Nice little post. You can easily improve this by checking the divisions by zero. :)
Thnx for suggesting. Are you saying that it should give infinity on dividing with zero?
That's entirely up to you. You can make it so it refuses the operands and displays an error or you can make it return infinity.
In any case, with the current code, the behavior when dividing by 0 is not what you can expect.
Actually on dividing by zero it is giving infinity as an output check it on compiler version gcc 6.3.0