In this I will tell you how to make a simple calculator just by using if-else in c language .First I tell you about if-else condition .You can easily understand it let us consider an example if(age>18) Then you can ride bike . This condition you have to meet in order to ride bike similarly in programming .If condition is true then you should do this other wise check for next condition .Using this we can also design calculator
Code:
#include <stdio.h>
int main()
{
float number1, number2;
char sign;
printf("Enter number1\n");
scanf("%f", &number1);
printf("Enter number second\n");
scanf("%f", &number2);
printf("Enter operator(*,-,+,/)\n");
scanf(" %c", &sign);
if (sign == '+')
{
printf("\nSum : %.2f", number1 + number2);
}
else if (sign == '-')
{
printf("\nDifferece: %.2f", number1 - number2);
}
else if (sign == '*')
{
printf("\nMultiply: %.2f", number1 * number2);
}
else if (sign == '/')
{
printf("\nDivision : %.2f", number1 / number2);
}
return 0;
}
Logic:
Now I will tell you what I do here .First I define three variables number1,number2 of type float and sign is of type character .If you does not know what variable is you can check my previous post where I do brief coverage of this topic .You can check here some brief Idea .Now back to this then I take value
of sign variable which can be(*,+,-,/) these are basic operator in c language. Then I ask user to enter number1 and number2.Then using if condition I check for every operator user can enter. Then If match is found then perform that operation .And in each match condition I give a print statement to output to user .
Output:
Here I show you output how it give us result . Make this program on your pc and run it .
I hope you might find this helpful .
Thanks for reading
No comments:
Post a Comment