Create a fraction calculator that takes input of two fraction and perform
the operation select by the user
First create two char array that is used to take the input in fraction from user and then user input the
operation to be performed like (+,-,/,*). your program should print the menu like below
Sample Input: Enter The first fraction value : 2/5
Sample Output: Enter The second Fraction Value : 2/5
CODE:
#include<stdio.h>
main()
{
// Variable declaration//
char a[3];
char b[3];
char c[3];
int i,sum=0,j=0,choice,sum1,temp;
float total,sum2,sum3;
for(i=0;i<3;i++) // here I intail array a and b with null
{
a[i]='\0';
b[i]='\0';
}
/*Input*/
printf("Enter 1st fraction:");
gets(a);
/* actual Working */
for(i=0;a[i]!='\0';i++)// this loop will convert asii to integer
{
if(a[i]>=48 && a[i]<=57 ) //if a arrry greater than 48 and less than 57 than this conition will run
{
c[j]=a[i]-48; //here I subtract 48 from a element and save it in c element
j++;
}
}
printf("Enter second fraction:");
gets(b);
for(i=0;i<3;i++)//this loop will work as same which I work ar above
{
if(b[i]>=48 && b[i]<=57)
{
b[i]=b[i]-48;
}
}
printf("Press 1 for Addition\nPress 2 for Substraction\nPress 3 for Multiplication\nPress 4 for division\n");
scanf("%d",&choice);//here what you want to perform
if(choice==1)
{
if(c[1]!=b[2])//if first fraction denominator is not same as second denominator so this condtion will work
{
b[0]=b[0]*c[1];
c[0]=c[0]*b[2];
sum=c[0]+b[0];
b[2]=c[1]*b[2];
c[1]=c[1]*b[2];
}
else{
sum=c[0]+b[0];
}
if(sum%2==0 && c[1]%2==0) //this condition will cheak that denominator or numerator divide by 2 or not
{
sum=sum/2;
b[2]=b[2]/2;
}
if(sum%3==0 && c[1]%3==0) //this condition will cheak that denominator or numerator divide by 3 or not
{
sum=sum/3;
b[2]=b[2]/3;
}
printf("Result:%d/%d",sum,b[2]);
}
else if(choice==2) //if choice equal to substraction so this condtion will perform
{
if(c[1]!=b[2])
{
c[0]=c[0]*b[2];//here I set first fraction NUMERATOR multiply by second fraction denominator
b[0]=b[0]*c[1];
temp=c[1];
c[1]=c[1]*b[2];
b[2]=temp*b[2];
sum=c[0]-b[0];
}
else{
sum=c[0]-b[0];
}
if(sum%2==0 && c[1]%2==0)
{
sum=sum/2;
c[1]=c[1]/2;
}
if(sum%2==0 && c[1]%2==0)
{
sum=sum/2;
c[1]=c[1]/2;
}
if(sum%3==0 && c[1]%3==0)
{
sum=sum/3;
c[1]=c[1]/3;
}
printf("Result:%d/%d",sum,c[1]);
}
else if(choice==3)
{
sum=c[0]*b[0];
sum1=b[2]*c[1];
printf("Result:%d/%d",sum,sum1);
}
else if(choice==4)
{
temp=b[0];
b[0]=b[2];
b[2]=temp;
c[0]=c[0]*b[0];
c[1]=c[1]*b[2];
printf("%d",c[0]);
total=c[0]/c[1];
printf("Result:%.2f",total);
}
else
{
printf("Invalid choice");
}
return 0;
}
Program Output:
For more problems click here
No comments:
Post a Comment