Making simple calculator in C - c

I'm making a simple calculator in C with operators +-*/. I tried to make a calculator but I have some problem with using do..while. I think while (op != 'A', 'Q', 'M', 'D', 'S'); is incorrect. What should I require here?
#include<stdio.h>
int main(void)
{
int x, y, result;
char op;
printf("****************\n");
printf("A-----Add\n");
printf("S-----Substract\n");
printf("M-----MUltiply\n");
printf("D-----Divide\n");
printf("Q-----Quit\n");
printf("****************\n");
printf("Enter the operation:");
scanf("%c", &op);
printf("Enter the two variables:");
scanf("%d %d", &x, &y);
do {
if (op == 'A')
result = x + y;
else if (op == 'S')
result = x - y;
else if (op == 'M')
result = x*y;
else if (op == 'D')
result = x / y;
else if (op == 'Q')
break;
} while (op != 'A', 'Q', 'M', 'D', 'S');
printf("%d %c %d = %d\n", x, op, x, result);
return 0;
}

!= is a binary operator, it takes one value on the left and one value on the right. You can't compare multiple values at once by just listing several values on the right.
To get this code working with minimal changes, you can compare op to each the variables individually, and combine them using the standard logical operators (e.g. &&).
You also need to think about the logic of your code. You're using a do ... while loop, which means that code will run at least once, and each time it reaches the end it will run again if the while condition is true. What happens after its first run? What happens if the user input (op) is none of the options specified? And you've got a 'quit' option, but what happens when it's used?

Four issues:
This: while (op != 'A', 'Q', 'M', 'D', 'S') doesn't do what you expect. You need to compare op against each value individually and do a logical AND (&&) between them.
If you don't enter a proper letter, your while loop will be an infinite loop because the prompt for user data is outside of the loop instead of inside. Move the printf and scanf calls to the inside of the loop.
If you do get an invalid input, the newline pressed by the user will get read in as the value to the first scanf. Put a blank space at the beginning of each scanf pattern to eat any newlines that may be in the buffer.
When you're printing the result, you're printing x as the second operand instead of y.
When you apply the above, you should have this:
#include<stdio.h>
int main(void)
{
int x, y, result;
char op;
printf("****************\n");
printf("A-----Add\n");
printf("S-----Substract\n");
printf("M-----MUltiply\n");
printf("D-----Divide\n");
printf("Q-----Quit\n");
printf("****************\n");
do {
// these four lines go inside the loop to prompt again
printf("Enter the operation:");
scanf(" %c", &op); // the space at the start eats the newline
printf("Enter the two variables:");
scanf(" %d %d", &x, &y); // the space at the start eats the newline
if (op == 'A')
result = x + y;
else if (op == 'S')
result = x - y;
else if (op == 'M')
result = x*y;
else if (op == 'D')
result = x / y;
else if (op == 'Q')
break;
// compare op against each value individually
} while (op != 'A' && op != 'Q' && op != 'M' && op != 'D' && op != 'S');
printf("%d %c %d = %d\n", x, op, y, result);
return 0;
}

while (op != 'A' && op != 'Q' && op !='M' && op !='D' && op !='S');

Related

How to do loop menu in C

I'm trying to do loop menu with some basic functions, everything is working fine apart of looping menu
in my opinion i have something wrong with while loop but i can't figure out what it is.
int main(void) {
char letter;
char status = 0;
printf ("--------------------------------------\n");
printf("a – Calculate the area of a rectangle\n");
printf("b – Calculate the area of a circle\n");
printf("c – Display a multiplication table\n");
printf("d – Add two numbers\n");
printf("x - exit program\n");
printf ("--------------------------------------\n");
scanf("%c",&letter);
while (status == 0)
{
if (letter == 'a' || letter == 'A')
{
}
if (letter == 'b'|| letter == 'B')
{
}
if(letter == 'c'|| letter == 'C')
{
}
if (letter == 'd'|| letter == 'D')
{
}
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
break;
}
status ++
}
return 0;
}
You need to pace a scanf(" %c",&letter); inside the loop body; otherwise, you will not get a chance to ever enter an x...
Please note the space before the %c, i.e. the " %c"-format, which captures any new line in the input buffer from a previous input.
Maybe you meant that status will be int and not char?
You should read input also in the beginning of loop, otherwise you will take only one input
After the first iteration, you advance status so it will exit the loop. Is this what you tried to achieve? I guess you meant for:
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
status ++
break;
}
Your loop will run only one time cause 'status ++' will work no matter the condition you should use it inside the x case -
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
status ++;
}
This should break your loop only after 'x' is entered.

scanf() in loop with a conditional does not work

I'm making a simple program that returns the sum of the sizes of user input.
User first inputs an int for amount of sizeof() sums to add
Followed by an input and char for data type.
This all works, BUT, what fails is if user types in anything other than 'c', 'd' or 'i' loop breaks and prints "invalid tracking code type."
My program fails on the conditional - even though the scanf() correctly obtains the char, it still fails.
FOR EXAMPLE:
INPUT:
3
10 i
7 c
12 d
OUTPUT
143 bytes
INPUT
1
1 o
OUTPUT
invalid tracking code type
how can you compare a user input using scanf in a loop?
#include <stdio.h>
int main()
{
int num, input, i, sum;
int invalid = 1;
sum = 0;
i = 0;
char type;
printf("give me a num!\n");
scanf("%d", &num);
while(i < num)
{
printf("int and char?\n");
//scanf("%d", &input);
//scanf(" %c\n", &type);
if (scanf("%d %c", &input, &type) != 2)
{
printf("TYPE IS: %c\n", type);
}
printf("TYPE IS: %c\n", type);
if(type != 'c' || type != 'd' || type != 'i')
{
printf("invalid tracking code type");
invalid = 0;
break;
}
i++;
//printf("what is i? %d\n", i);
sum = (sizeof(input)) + sum;
printf("IT's the sum %d\n", sum);
}
if(invalid != 0)
{
printf("%d bytes", sum);
}
return 0;
}
There are a number of other posts that answer similar issues, but wasn't able to find anything specifically for this issue.
I've tried a number of things such as separating the scanf(), using different types of operators for the conditional. It works fine without the conditional, but with the conditional it always returns "invalid tracking code type" even when they are correct.
Replace
if(type != 'c' || type != 'd' || type != 'i')
By
if(type != 'c' && type != 'd' && type != 'i')

Evaluate an expression, users can enter as many numbers and operators as they want

This is the Programming Project 7.12 of the C Programming - A Modern Approach. The program is expected to evaluate an expression (for example 1+2.5*3) and return its result (10.5 in this case, note that the expression is evaluated from left to right, and no operator takes precedence over any other operator).
This is what I've tried (the expression is 1 + 2.5 *3, for example): store 1 in a, + in ch, and 2.5 in b. Then let result = a, compute the "new" result by either adding, subtracting, dividing or multiplying with b. Then continue reading the expression, storing * in ch, and 3 in b. Run the while loop again until the scanf detects a new-line character. I wonder what is wrong with my method, or my code.
#include <stdio.h>
int main(void)
{
float a, b, result;
char ch;
printf("Enter an expression: ");
scanf("%f%c%f", &a, &ch, &b);
result = a;
while (ch != '\n') {
if (ch == '+')
result += b;
else if (ch == '-')
result -= b;
else if (ch == '*')
result *= b;
else if (ch == '/') {
result /= b; }
scanf("%c", &ch);
scanf("%f", &b);
}
printf("Value of expression: %.2f", result);
return 0;
}
It doesn't return anything :(
Even after you press enter after putting complete expression.
scanf("%c", &ch);
scanf("%f", &b);
Will still wait to input float because of order of scanf.
Just break immediately once you press enter as below.
while (ch != '\n') {
if (ch == '+')
result += b;
else if (ch == '-')
result -= b;
else if (ch == '*')
result *= b;
else if (ch == '/') {
result /= b; }
scanf("%c", &ch);
if (ch == '\n') break;
scanf("%f", &b);
}
I would suggest you to use fgets to read the complete expression at
once and process the expression afterwards also your current code is very naive wouldn't even work for complex expression which includes (, ) etc, you may want to use LIFO data structure by processing the read expression in reverse order.

How can I use scanf to input coordinates and also a character if needed within this function

How can I have player one input coordinates (x,y) (1,2) while also being able to have the option to input a character such as 'c' or 's'?
I can change x to char and then use %c for the first input and then have if (x =='1') x = 1 and so on, but it still will give me segmentation fault because it needs to scan something in for y. How can I fix this?
matrix[][] is a global char 2d array.
void updateTablePlayer1(void)
{
int y, x;
printf ("Enter a command for player 1 ([row,col], c, s, p):");
scanf ("%d,%d", &x, &y);
x--;
y--;
if (matrix[x][y]!= ' ')
{
printf ("Invalid selection\n");
updateTablePlayer1();
{
else if (x == 'c')
{
createClearTable();
displayTable();
updateTablePlayer1();
}
else if (x == 's')
{
displayTable();
updateTablePlayer1();
}
else if (x == 'p')
{
displayTableImage();
updateTablePlayer1();
}
else
matrix[x][y] = 'X';
}
There is a place call scanf()-land that is evil, surround by sharks and crawling with snakes. Tortured sad code bodies are littered about.
There is a happier place called fgets()-land. It has a few bumps and pitfalls, but is much safer - code with long old grey beards live there.
Step 1: flush the output to insure buffering does not prevent it from being shown after input
printf ("Enter a command for player 1 ([row,col], c, s, p):");
fflush(stdout);
Step 2: Read the line
// scanf ("%d,%d", &x, &y);
char buffer[80];
if (fgets(buffer, sizeof buffer, stdin) == NULL) Handle_input_closed();
Step 3: Parse the input. Always check for errors.
int x,y;
char command;
if (sscanf(buffer, "%d,%d", &x, &y) == 2) {
Do_xy_Stuff();
}
else if (sscanf(buffer, " %c", &command) == 1) {
if (command == 'c') Do_c_Stuff();
else if (command == 's') Do_s_Stuff();
else if (command == 'p') Do_p_Stuff();
else Complain_about_bad_input();
} else {
Complain_about_bad_input();
}
Your scanf call is doing two things: reading in some input, and interpreting it as numbers. Separate these two things: read in a string, and then interpret it.
It is probably better to use fgets rather than scanf for reading in the string. When your input looks like it contains numbers, you could use sscanf to decode them.

Issues with if/else statements in C

Trying to write a simple calculater in C. I'm stuck in having the program terminated if letter 'A', 'B', 'C' or 'D' is not entered, otherwise continue. Even though I enter a valid character it never proceeds.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char letter;
float num1,num2;
printf("What operation would you like to perform?\n\tA) Addition\n\tB) Subtraction\n\tC) Multiplication\n\tD) Division\n\n");
scanf("%c", &letter);
if (letter != 'A' || letter != 'B' || letter != 'C' || letter != 'D')
printf("Not a valid operation\n");
return 1;
printf("Please enter first number: ");
scanf("%f", &num1);
printf("Please enter second number: ");
scanf("%f", &num2);
if (letter == 'A' || letter == 'a')
printf("The sum of %f and %f, is %f\n", num1, num2, num1 + num2);
else if (letter == 'B' || letter == 'b')
printf("The difference of %f and %f, is %f\n", num1, num2, num1 - num2);
else if (letter == 'C' || letter == 'c')
printf("The product of %f and %f, is %f\n", num1, num2, num1 * num2);
else if (letter == 'D' || letter == 'd')
printf("The quoation of %f and %f, is %f\n", num1, num2, num1 / num2);
else
printf("The operation was not valid");
return 0;
}
Thank you for your help.
if (letter != 'A' || letter != 'B' || letter != 'C' || letter != 'D')
printf("Not a valid operation\n");
return 1;
This part is the problem. Although return 1; is indented, it will execute regardless because it is not part of the if block. Additionally, you are using the wrong operator, your condition statement reads "if letter is not A or letter is not B ..." which is always going to be true because letter cannot be both A and B at the same time. You need to envelope the two statements and use the && operator instead, like this:
if (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D')
{
printf("Not a valid operation\n");
return 1;
}
In C, indentation is meaningless to the compiler. If you need to execute multiple statements as a result of a condition, they must be wrapped up into a compound statement using { and }.
You check
if (letter != 'A' || letter != 'B' ...)
Ok - if letter is 'B', then it is not A, and the program stops testing there and prints your failure condition and returns.
On the other hand, if letter was 'A', it would not be 'B', and so it would fail the second test instead, and fail there.
What you want:
if (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D')
Alternately, you could use the C function "strchr" which searches for a character in a string.
if (!strchr("ABCDabcd", letter)) // returns NULL, which is false, if no match
{
printf("Invalid operation");
return 1;
}
Try:
if (letter != 'A' && letter != 'B' && letter != 'C' && letter != 'D')
...

Resources