C calculator if else - c

I want to make a simple C calculator only with "IF" and "IF ELSE" conditions and it don't let me choose an operator ("+, -, * or /"), just appear my last if condition.
#include <stdio.h>
int main(){
printf("\tCalculadora\n\n");
int num1, num2, total;
char oper;
printf("Introduza o primeiro numero: \n");
scanf("%d", &num1);
printf("Introduza o segundo numero: \n");
scanf("%d", &num2);
printf("Escolha a operacao que quer realizar!\n\n");
scanf("%c", &oper);
if(oper == '+'){
printf("O resultado e: %d", num1+num2);
}
else if(oper == '-'){
printf("O resultado e: %d", num1-num2);
}
else if(oper == '*'){
printf("O resultado e: %d", num1*num2);
}
else{
printf("O resultado e: %d", num1/num2);
}
getchar();
getchar();
}

I avoid scanf() and its cousins. Here is a version of your calculator that uses fgets() for the input. It also uses double for the operands.
#include <stdio.h>
#include <stdlib.h>
#define ISIZE 100 // arbitrarily large
int main(){
double num1, num2;
int oper;
char inp[ISIZE+1] = "";
printf("\tCalculadora\n\n");
printf("Introduza o primeiro numero: "); // 1st operand
fgets (inp, ISIZE, stdin);
num1 = atof (inp);
printf("Introduza o segundo numero: "); // 2nd operand
fgets (inp, ISIZE, stdin);
num2 = atof (inp);
printf("Escolha a operacao que quer realizar! "); // operator
fgets (inp, ISIZE, stdin);
oper = inp[0];
printf ("O resultado e: %f %c %f = ", num1, oper, num2);
switch (oper) {
case '+': printf("%f\n", num1+num2); break;
case '-': printf("%f\n", num1-num2); break;
case '*': printf("%f\n", num1*num2); break;
case '/': if (num2!=0) printf("%f\n", num1/num2);
else printf ("Divisão por zero!\n");
break;
default: printf("Eu não sei o que operador\n");
}
return 0;
}

This
scanf("%c", &oper);
should change to
scanf(" %c", &oper);
so you let scanf() ignore the '\n' left by previous scanf()s.

I was also trying to apply my knowladage of C in a simple calculator and came across you question. In order to respect your if...else request I've come up with this solution. I hope this helps.
#include <stdio.h>
void sayHello( ) {
printf("Hello\n"); }
// to say hello to the user
int add( int num1, int num2) {
num1 = num1 + num2;
return num1;
}
int minus( int num1, int num2) {
num1 = num1 - num2;
return num1;
}
int times( int num1, int num2) {
num1 = num1 * num2;
return num1;
}
int divide( int num1, int num2) {
num1 = num1 / num2;
return num1;
}
// This is to declare the calculations
void flush_input(){
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); }
// This is to flush the scanf values
// Kudos to Huw Collingbourne, Udemy Teacher
int main(int argc, char **argv) {
char c;
char f;
int n1;
int n2;
int total;
// n1 = ' ';
// n2 = ' ';
sayHello();
do {
c = ' ';
printf("Insert the type of Calculation you want to make:\n");
printf("A(d)dition, Subs(t)raction, Mu(l)tiplication, Di(v)ision: ");
c = getchar();
if(c == 'd') {
printf("\nInsert the first number:");
scanf("%d", &n1);
printf("Insert the second number:");
scanf("%d", &n2);
total = add( n1, n2 );
printf("%d plus %d equals to %d\n", n1, n2, total );
flush_input(); } else {
if( c == 't') {
printf("insert the base number:");
scanf("%d", &n1);
printf("Insert the subtracting number:");
scanf("%d", &n2);
total = minus( n1, n2 );
printf("The difference between %d and %d is %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'l') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = times( n1, n2 );
printf("%d times %d equals %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'v') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = divide( n1, n2 );
printf("%d divided by %d equals %d\n", n1, n2, total );
flush_input();
} else {
printf("I couln't understand the instruction\n Reseting program\n");
}
}
}
}
f = ' ';
printf("\nDo you wish to make another calculation?\n");
printf("Choose (y)es or (n)ot: ");
f = getchar();
// scanf("%c", &c);
getchar();
} while( f != 'n' );
printf("\nThat's all folks!\n");
return 0;
}

#include <stdio.h>
#include <stdlib.h>
//declaration of function
float cal (float a, float b, char o);
int main(int argc, char *argv[])
{
// declaration of variable
float num1,num2;
int inum1,inum2;
char o;
//initialization of variable
num1=0;
num2=0;
//input
printf("Enter 1st number\n");
scanf("%f",&num1);
//input
printf("operator\n");
scanf(" %c", &o);
//input
printf("Enter 2nd number\n");
scanf(" %f", &num2);
inum1=num1;
inum2=num2;
if(cal(num1,num2,o)==0)
{
printf("Math Error");
}
if(cal(num1,num2,o)==1)
{
printf("%d",inum1%inum2);
}
else
printf("%.3f\n",cal(num1,num2,o));
return 0;
}
//definening function
float cal (float a, float b, char o)
{
if (o=='+')
return a+b;
if (o=='-')
return a-b;
if (o=='*')
return a*b;
if (o=='%')
return 1;
if (o=='/')
if (b!=0)
return a/b;
if (b==0)
return 0;
}

Related

Switch/Case exiting the code working when I type in the console C

I am trying to make a basic console script for a calculator as a starter C project. When I type anything after the printf("\nOperator: "); Nothing happens it just exits the program. This shouldn't happen because of the switch statement at line 45
Language: C
Compiler: GCC
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <Windows.h>
int main()
{
// Variables
int x;
int y;
char op = ' ';
int sum;
int difference;
int product;
int quotient;
int sqrta;
int logarithm;
int exponent;
// Functions
printf("**FxrMath**\n");
printf("");
printf("Options:\n");
printf("(A)dd\n");
printf("(S)ubtract\n");
printf("(M)ultiply\n");
printf("(D)ivide\n");
printf("S(q)uare Root\n");
printf("(L)ogarithm\n");
printf("(P)ower (x^y)\n");
printf("(H)ypotoneuse Calculator");
printf("\n");
printf("\n**OPERATOR MUST BE LOWERCASE**");
printf("\n");
printf("\nOperator: ");
scanf("%d", &op);
switch (op) // Checking what to do
{
case 'a':
printf("First Number: ");
scanf("%d", &x);
printf("\nSecond Number: ");
scanf("%d", "&d", &y);
int sum = x + y;
printf("\n%dSum: ", sum);
Sleep(2500);
break;
case 's':
printf("First Number: ");
scanf("%d", &x);
printf("\nSecond Number: ");
scanf("%d", &y);
int difference = x - y;
printf("\n%dDifference: ", difference);
Sleep(2500);
break;
case 'm':
printf("First Number: ");
scanf("%d", &x);
printf("\nSecond Number: ");
scanf("%d", &y);
int product = x * y;
printf("\n%dProduct: ", product);
Sleep(2500);
break;
case 'd':
printf("First Number: ");
scanf("%d", &x);
printf("\nSecond Number: ");
scanf("%d", &y);
int quotient = x / y;
printf("\n%dQuotient: ", quotient);
Sleep(2500);
break;
case 'q':
printf("Number: ");
scanf("%d", &x);
int sqrta = sqrt(x);
printf("\n%dSquare Root: ", sqrta);
Sleep(2500);
break;
case 'l':
printf("First Number: ");
scanf("%d", &x);
int logarithm = log(x);
printf("\n%dLogarithm: ", logarithm);
Sleep(2500);
break;
case 'p':
printf("First Number: ");
scanf("%d", &x);
printf("\nSecond Number: ");
scanf("%d", &y);
int exponent = pow(x, y);
printf("\n%dExponent: ", exponent);
Sleep(2500);
break;
case 'h':
int a;
int b;
printf("\nA: ");
scanf("%d", a);
printf("\nB: ");
scanf("%d", b);
double hypotenuse = sqrt((a*a) + (b*b));
printf("\n%dHypotenuse: ", hypotenuse);
Sleep(2500);
break;
default:
break;
}
return 0;
}
The variable op is declared as having the type char
char op = ' ';
So this call of scanf
scanf("%d", &op);
is incorrect. Firstly the function expects an argument of the type int and secondly entering a symbols will not be successful.
Instead write
scanf( " %c", &op );
Pay attention to the leading space in the format string. It allows to skip automatically white space characters in the input buffer.
Also such a call of scanf
scanf("%d", "&d", &y);
also is incorrect. It seems you mean
scanf("%d", &y);
And these variable declarations
int sum;
int difference;
int product;
int quotient;
int sqrta;
int logarithm;
int exponent;
are redundant because in each code snippet under a case label you declared a corresponding variable one more as for example
case 'a':
printf("First Number: ");
scanf("%d", &x);
printf("\nSecond Number: ");
scanf("%d", "&d", &y);
int sum = x + y;
^^^^^^^
And such declarations must be enclosed in block scopes as for example
case 'a':
{
printf("First Number: ");
scanf("%d", &x);
printf("\nSecond Number: ");
scanf("%d", "&d", &y);
int sum = x + y;
//...
break;
}

Is there an easy way to return the user to the menu after each selection?

My program is supposed to ask the user to make a selection and run the selection before returning back to the menu. I figure I need break statements but wouldn't I need to change all the if statements to do that? Right now it runs through all the selections immediately without stopping. Is there an easy fix to this or do I go back and rewrite each statement? Here is what I have so far:
#include <stdio.h>
#include <math.h>
int main()
{
int choice;
int i, j, k, l;
int num, num2, num3, num4;
int count = 0;
printf("\t Menu \n");
printf("1. Multiplication Table \n");
printf("2. Even or Odd \n");
printf("3. Number of Digits \n");
printf("4. Triangle \n");
printf("5. Exit \n");
printf("Please choose a menu selection: \n");
scanf("%d", &choice);
if(choice = 1);
{
for(i = 1; i <= 12; i++)
{
num = i;
for(j = 1; j<=12; j++)
{
printf("%d\t", (i*j));
}
printf("\n");
}
}
if(choice = 2);
{
printf("Please enter a whole number: \n");
scanf("%d", &num2);
if(num2 % 2 == 0)
printf("%d is even. \n", num2);
else
printf("%d is odd. \n", num2);
}
if(choice = 3);
{
printf("Enter a number: \n");
scanf("%d", &num3);
while(num3)
{
num3 = num3/10;
count++;
}
printf("The total number of digits in the number is: %d \n", count);
}
if(choice = 4);
{
printf("Please enter a number for the height: \n");
scanf("%d", &num4);
for(k = 1; k <= num4; k++)
{
for(l = 1; l <= k; l++)
printf("# ");
printf("\n");
}
}
if(choice = 5)
{
printf("Thank you, you will now exit. \n");
}
else
{
printf("error \n");
}
return 0;
}
#include <math.h>
int main()
{
int choice;
int i, j, k, l;
int num, num2, num3, num4;
int count = 0;
do{
printf("\t Menu \n");
printf("1. Multiplication Table \n");
printf("2. Even or Odd \n");
printf("3. Number of Digits \n");
printf("4. Triangle \n");
printf("5. Exit \n");
printf("Please choose a menu selection: \n");
scanf("%d", &choice);
switch(choice){
case 1:
{
for(i = 1; i <= 12; i++)
{
num = i;
for(j = 1; j<=12; j++)
{
printf("%d\t", (i*j));
}
printf("\n");
}
} break;
case 2:
{
printf("Please enter a whole number: \n");
scanf("%d", &num2);
if(num2 % 2 == 0)
printf("%d is even. \n", num2);
else
printf("%d is odd. \n", num2);
}break;
case 3:
{
printf("Enter a number: \n");
scanf("%d", &num3);
while(num3)
{
num3 = num3/10;
count++;
}
printf("The total number of digits in the number is: %d \n", count);
}break;
case 4:
{
printf("Please enter a number for the height: \n");
scanf("%d", &num4);
for(k = 1; k <= num4; k++)
{
for(l = 1; l <= k; l++)
printf("# ");
printf("\n");
}
}break;
case 5:
{
printf("Thank you, you will now exit. \n");
}break;
}
} while(choice < 5 && choice > 0);
if(choice>5 || choice<=0)
printf("error \n");
return 0;
}

Storing Char and using it in if-statements

I just wanna know how to save or store a symbol such as +, -, / and * so that i could use it in if-statements to perform whatever symbol the user inputs. I know that my code is wrong so any kind of help will be appreciated.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int int1, int2, sum;
char oper;
printf("Enter Value Here: ");
scanf("%d", &int1);
printf("Enter Operation Here: ");
scanf("%s", &oper);
printf("Enter Value Here: ");
scanf("%d", &int2);
if (oper == "+")
sum = int1 + int2;
printf("The sum is %d", sum);
return 0;
}
You could do something like this:
#include<stdio.h>
int main(void){
int int1, int2, sum=0;
char op;
printf("Please enter one of the following Operators [*] [/] [+] [-] ");
if((scanf("%c",&op)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%d", &int1)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%d", &int2)) != 1){
printf("Error\n");
}
if (op == '/'){
sum = int1 / int2;
}else if(op == '*'){
sum = int1 * int2;
}else if(op == '+'){
sum = int1 + int2;
}else if(op == '*'){
sum = int1 - int2;
}
printf("The sum is %d\n", sum);
return 0;
}
Edit:
For a better precision you can use float or double, Use double if you are not sure.
#include<stdio.h>
int main(void){
float int1, int2, sum=0;
char op;
printf("Please enter one of the following Operators [*] [/] [+] [-] ");
if((scanf("%c",&op)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%f", &int1)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%f", &int2)) != 1){
printf("Error\n");
}
if (op == '/'){
sum = int1 / int2;
}else if(op == '*'){
sum = int1 * int2;
}else if(op == '+'){
sum = int1 + int2;
}else if(op == '*'){
sum = int1 - int2;
}
printf("The sum is %.1f\n", sum);
return 0;
}
Most likely you are looking for a function pointers that will let you do some object oriented programming:
// type of functions being binary operations
typedef int (binary_operation*)(int, int);
// now you can define any binary operation on ints
int add_op(int a, int b) { // definition };
int mul_op(int a, int b) { // definition };
// main...
binary_operation f;
if (oper == "+")
f = add_op;
sum = f(in1,int2);
This way you can store your functions in container, you can pass them to other functions and so on.
why don't you use switch case in C:
char oper;
float num1,num2;
printf("Enter operator either + or - or * or / : ");
scanf("%c",&oper);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(oper) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
now using if-else:
//same code
scanf("%f%f",&num1,&num2);
if(oper=='+')
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
else if(oper=='-')
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
else if(oper=='*')
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
else if(oper=='/')
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
else
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");

Loop Run Wrong In Main Function

When i run the code,in main function something going wrong.After first round of loop in main,program print "Wrong Choice" altough choice is legal.
#include <stdio.h>
#include <stdlib.h>
int factorial(int n);
void prime_numbers(){
int upper_bound;
printf("Define upper bound:");
scanf("%d",&upper_bound);
printf("Prime Numbers: ");
int i,j;
int variable;
for (i=2;i<=upper_bound;i++)
{
variable = 1;
for (j = 2; j <i; j++)
{ if (i % j == 0)
{
variable = 0;
break;
}
}
if (variable == 1)
printf ("%d ", i );
}
printf("\n");
}
void leibniz_series(){
printf("Define k value:");
int k;
scanf("%d",&k);
double sum=0;
int i;
for (i=1; i<k; i++)
{
if ((i%2)==1)
sum=sum+1.0/((2.0 * (double)i) - 1.0);
else
sum = sum - 1.0/((2.0 * (double)i) - 1.0);
}
printf("Result:%f\n",4*sum);
}
void combination(){
int comb;
printf("Define n and r:");
int n,r;
scanf("%d %d",&n,&r);
comb=factorial(n)/(factorial(r)*factorial(n-r));
printf("Result:%d ",comb);
printf("\n");
}
int factorial(int n){
int f=1;
int i;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
int main()
{
printf("Press P or p for Prime Numbers\n");
printf("Press L or l for Leibniz Series\n");
printf("Press C or c for Combinations\n");
printf("Press E or e for Exit\n");
char choice;
for(;;){
printf("Enter your choice:");
scanf("%c",&choice);
if(choice=='E' || choice=='e')
exit(0);
switch(choice){
case 'p' : prime_numbers();
break;
case 'P' : prime_numbers();
break;
case 'l' : leibniz_series();
break;
case 'L' : leibniz_series();
break;
case 'c' : combination();
break;
case 'C' : combination();
break;
default : printf("Wrong choice\n");
}
}
return 0;
}
It is probably something to do with the return key you pressed to enter the input lying around in your input buffer.
To simply clear that character from the buffer you can read it and ignore it by adding scanf("%*c"); immediately after you scan for a character from the STDIN.
So your new code would look something like this:
printf("Enter your choice:");
scanf("%c",&choice);
scanf("%*c");

Switch case program does not give the output

#include<stdio.h>
int main()
{
int choice;
printf("Enter 1 for Programmers Name and ID\n");
printf("Enter 2 to Perform Integer Operation\n");
printf("Enter 3 to Perform Floating Point Operation\n");
scanf("%d", &choice);
system("CLS");
if (choice == 1)
printf("Connor \n000000000\n");
else if (choice == 2)
{
char c;
int num1, num2;
printf("Enter operator:");
scanf("%c", &c);
getchar();
printf("Enter two integer's :");
scanf("%d %d", &num1, &num2);
switch (c)
{
case '+':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case '-':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case '*':
printf("%d * %d = %d", num1, num2, num1*num2);
break;
case '/':
printf("%d / %d = %d", num1, num2, num1 / num2);
break;
default:
printf("The value of c = '%c'\n");
system("pause");
return(0);
}
}
else if (choice == 3)
printf("Enter two \n");
system("pause");
return(0);
}
I need a little help figuring out a small problem with the operations part of this code.......everything works out as in can put in the operator and the integers but I do not get the output from the switch.
this should definitely work
#include<stdio.h>
int main()
{
int choice;
printf("Enter 1 for Programmers Name and ID\n");
printf("Enter 2 to Perform Integer Operation\n");
printf("Enter 3 to Perform Floating Point Operation\n");
scanf("%d", &choice);
getchar();
if (choice == 1)
printf("Connor \n000000000\n");
else if (choice == 2)
{
char c;
int num1, num2;
printf("Enter operator:");
scanf("%c", &c);
printf("Enter two integer's :");
scanf("%d %d", &num1, &num2);
switch (c)
{
case '+':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case '-':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case '*':
printf("%d * %d = %d", num1, num2, num1*num2);
break;
case '/':
printf("%d / %d = %d", num1, num2, num1 / num2);
break;
default:
printf("The value of c = '%c'\n" , c);
return(0);
}
}
else if (choice == 3)
printf("Enter two \n");
}
Change:
scanf("%c", &c);
getchar();
to:
scanf(" %c", &c);
Add an \n to each of these:
printf("%d + %d = %d\n", num1, num2, num1 + num2);
^^
Actually provide a char when you tell printf() to print one:
printf("The value of c = '%c'\n", c);
^^^
and it should work for you. Revised code, removing all the system() nonsense:
#include <stdio.h>
int main(void)
{
int choice;
printf("Enter 1 for Programmers Name and ID\n");
printf("Enter 2 to Perform Integer Operation\n");
printf("Enter 3 to Perform Floating Point Operation\n");
scanf("%d", &choice);
if ( choice == 1 ) {
printf("Connor \n000000000\n");
}
else if ( choice == 2 ) {
char c;
int num1, num2;
printf("Enter operator:");
scanf(" %c", &c);
printf("Enter two integers :");
scanf("%d %d", &num1, &num2);
switch ( c ) {
case '+':
printf("%d + %d = %d\n", num1, num2, num1 + num2);
break;
case '-':
printf("%d - %d = %d\n", num1, num2, num1 - num2);
break;
case '*':
printf("%d * %d = %d\n", num1, num2, num1 * num2);
break;
case '/':
printf("%d / %d = %d\n", num1, num2, num1 / num2);
break;
default:
printf("The value of c = '%c'\n", c);
break;
}
} else if ( choice == 3 ) {
printf("Enter two \n");
}
else {
printf("Invalid choice.\n");
}
return 0;
}
with sample output:
paul#thoth:~/src/sandbox$ ./cal
Enter 1 for Programmers Name and ID
Enter 2 to Perform Integer Operation
Enter 3 to Perform Floating Point Operation
2
Enter operator:*
Enter two integers :4 6
4 * 6 = 24
paul#thoth:~/src/sandbox$

Resources