Switch case program does not give the output - c

#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$

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;
}

Looping Calculator in C

I am just making a simple calculator and would like to know
how could I make my calculator loop back to the start when an invalid operator/float is entered; to ask the user to input everything again. Basically restarting it.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
double num1;
double num2;
char op;
printf("Input a number: ");
scanf("%lf", &num1);
printf("Enter operator (+,-,*,/,^): ");
scanf(" %c", &op);
printf("Enter the second number: ");
scanf(" %lf", &num2);
if (op == '+')
{
printf("%f", num1 + num2);
}
else if (op == '-')
{
printf("%f", num1 - num2);
}
else if (op == '/')
{
printf("%f", num1 / num2);
}
else if (op == '*')
{
printf("%f", num1 * num2);
}
else if (op == '^')
{
printf("%f", pow(num1,num2));
}
else
{
printf("Invalid operator entered");
}
return 0;
}
I would do it another way to avoid \n scanf problems
#define MAXNUMSTR 100
int calc(void)
{
char line[MAXNUMSTR];
double num1;
double num2;
double res;
do
{
printf("\nInput first number: ");
if(!fgets(line, MAXNUMSTR -1, stdin)) return 0;
}while(sscanf(line, "%lf", &num1) != 1);
do
{
printf("\nInput second number: ");
if(!fgets(line, MAXNUMSTR -1, stdin)) return 0;
}while(sscanf(line, "%lf", &num2) != 1);
printf("\nEnter operator (+,-,*,/,^, x): ");
if(!fgets(line, MAXNUMSTR -1, stdin)) return 0;
switch(line[0])
{
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
if(num2 == 0.0)
{
printf("\nDivision by zero\n");
return 1;
}
res = num1 / num2;
break;
case '^':
res = pow(num1, num2);
break;
case 'x':
return 0;
default:
printf("\nInvalid operation\n");
return 1;
}
printf("\n%f %c %f = %f\n", num1, num2, res);
return 1;
}
int main(void)
{
while(calc());
return 0;
}
Insert the whole logic in an infinite loop like below.
while(1) {
printf("Input a number: ");
scanf("%lf", &num1);
printf("Enter operator (+,-,*,/,^): ");
scanf(" %c", &op);
printf("Enter the second number: ");
scanf(" %lf", &num2);
if (op == '+')
{
printf("%f", num1 + num2);
}
else if (op == '-')
{
printf("%f", num1 - num2);
}
else if (op == '/')
{
printf("%f", num1 / num2);
}
else if (op == '*')
{
printf("%f", num1 * num2);
}
else if (op == '^')
{
printf("%f", pow(num1,num2));
}
else
{
printf("Invalid operator entered");
}
}

Switch case menu doesn`t exit program when type case

I've coded a calculator with a menu. I'm trying to use switch case. My problem is that the menu doesn't exit immediately with case 0 when the program is asking about values.
#include<stdio.h>
int main(void) {
float a = 0;
float b = 0;
int menu = 0;
mainMenu();
scanf_s(" %d", &menu);
printf("Give a A:\n");
scanf_s(" %f", &a);
printf("Give a B:\n");
scanf_s(" %f", &b);
switch (menu) {
case 0: {
printf("Choice: 0\n");
puts("Goodbye");
break;
}
case 1: {
printf("Choice: 1\n");
printf(" %f", add(a, b));
break;
}
case 2: {
printf("Choice: 2\n");
printf(" %f", sub(a, b));
break;
}
case 3: {
printf("Choice: 3\n");
printf(" %f", mul(a, b));
break;
}
case 4: {
printf("Choice: 4\n");
printf(" %f", div(a, b));
break;
}
default: {
printf("No action selected\n");
break;
}
}
return 0;
}
scanf_s(" %d", &menu);
if (menu == 0)
{
printf("Choice: 0\n");
puts("Goodbye");
return 0;
}
you need to check if the input for menu is given zero or no. If the input for menu is zero, just return from there. You don't need to go deep down for rest of the inputs.
as per comment of #bruceg, remove the case 0 from the switch.

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");

C calculator if else

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;
}

Resources