The below code will create a simple calculator with the use of if-else-if control structure.
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,mod;
float x,y,sum,sub,mul,div;
char ch,op;
printf("This is a calculator\nThe following operations can be perfoemed by it\n\naddition +\nsubtraction -\nmultiplication *\ndivision /\nremainder %%\n\nEnter your equation e.g \"3+4\" :");
scanf("%f %c %f",&x, &op,&y);
if(op=='+')
{
sum=x+y;
printf("anwser is %.2f",sum);
}
else if(op=='-')
{
sub=x-y;
printf("answer is %.2f",sub);
}
else if(op=='*')
{
mul=x*y;
printf("answer is %.2f",mul);
}
else if(op=='/')
{
if(x==0||y==0)
{
printf("The entered number should not be zero");
}
else
{
div=x/y;
printf("answer is %.2f",div);
}
}
else if(op=='%')
{
a=x;
b=y;
mod=a%b;
printf("mod is %d",mod);
}
else
printf("invalid input");
printf("\n\n\n(*_*) Would you like to run again...(Y/N)");
scanf(" %c",&ch);
if(ch=='Y'||ch=='y')
{
system("cls");
main();
}
printf("\npress any key to continue");
getch();
}
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,mod;
float x,y,sum,sub,mul,div;
char ch,op;
printf("This is a calculator\nThe following operations can be perfoemed by it\n\naddition +\nsubtraction -\nmultiplication *\ndivision /\nremainder %%\n\nEnter your equation e.g \"3+4\" :");
scanf("%f %c %f",&x, &op,&y);
if(op=='+')
{
sum=x+y;
printf("anwser is %.2f",sum);
}
else if(op=='-')
{
sub=x-y;
printf("answer is %.2f",sub);
}
else if(op=='*')
{
mul=x*y;
printf("answer is %.2f",mul);
}
else if(op=='/')
{
if(x==0||y==0)
{
printf("The entered number should not be zero");
}
else
{
div=x/y;
printf("answer is %.2f",div);
}
}
else if(op=='%')
{
a=x;
b=y;
mod=a%b;
printf("mod is %d",mod);
}
else
printf("invalid input");
printf("\n\n\n(*_*) Would you like to run again...(Y/N)");
scanf(" %c",&ch);
if(ch=='Y'||ch=='y')
{
system("cls");
main();
}
printf("\npress any key to continue");
getch();
}
Post a Comment