Comparing the characters [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am writing a code for solving arithmetic expression like:4+3-2*6*(3+4/2)
For that I need to compare the operators in the string with precedence like:
1. ( or )
2. * or /
3. + or -
Can someone tell me how to compare two characters. As their ASCII values are not in the order which I want!

Use a lookup table. If using ASCII, it is just a 256 element table. You index it with the char.

For that I need to compare the operators in the string with precedence
like:
You can do something like this to get a precedence for each character:
int get_precedence (char c) {
switch (c) {
case '+':
case '-': return 3;
case '*':
case '/': return 2;
case '(':
case ')': return 1;
default: return -1;
}
}
That makes it very easy to add in additonal characters as you need.
However, you'll still have some issues. For example, how will you tell unary negation from subtraction? You'll need to look at context for that, because the answer will depend on what comes before. Dealing with infix notation is hard.
To do this yourself, you'll want to write a recursive descent parser or use the shunting yard algorithm. Either way, it'll be several hundred lines of hard code. Then you'll need to decide if you evaluate from the abstract syntax tree or compile to byte code.
I am writing a code for solving arithmetic expression
like:4+3-2*6*(3+4/2)
If you want to solve that in an easy way, you should find a pre-existing library. TinyExpr is one such solution. It's open-source and contained in a single C source code file. Code for that would look like:
#include "tinyexpr.h"
double answer = te_interp("4+3-2*6*(3+4/2)", 0);

Even in ASCII, the order of the integers are still the same. You can compare single digits. For example:
if ('7' > '2') will evaluate to true

Related

Reverse an infix expression in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Such that a string of "23+45" becomes "45+23"?
This is in relation to converting an infix expression to prefix expression, with the goal here being to be able to first reverse the infix expression
The usual way to do so is to code some recursive descent parser building some concrete syntax tree in memory.
So you would first define several struct-s representing the various nodes of that tree (as a tagged union type), then code the parser, then code the transformation of nodes, then code their printer. Read wikipage on abstract syntax trees.
You may want to use parser generators like GNU bison or ANTLR.
You certainly should read books like the Dragon book before coding.
You should also read the documentation of your C compiler (e.g. GCC) and debugger (e.g. GDB)
You could take inspiration from the source code of existing open source programs like GNUmeric or octave or GNUplot or Lua or GNU guile or GNU bash.
PS. For a university homework, mention the source code you did study. Your teacher might be delighted you read them.
Here is a readable and easy to understand solution. It's not the most efficient, but if you are doing infix/postfix notations you are not concern with performance:
/* \brief swap in-place the operands of an expression of form `lhs op rhs` (no spaces)
* where op is a single character operator
*
* \param expr string representing the expression. Must follow specified form
* \param operator single character operator
*
* \post \p expr will contain `rhs op lhs` (no spaces)
*/
void reverse_expr(char* expr, char operator)
{
char* buffer = malloc(strlen(expr) + 1);
char* const operator_pos = strchr(expr, operator);
if (operator_pos == NULL)
{
fprintf(stderr, "invalid expression: missing '%c'", operator);
free(buffer);
exit(1);
}
*operator_pos = '\0';
sprintf(buffer, "%s+%s", expr, operator_pos + 1);
strcpy(expr, buffer);
free(buffer);
}

How can I delete the first zero(s) in a string? (Without using atoi) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I was making a script that is calculating the additions between two natural numbers which decimal lengths should be smaller or same with 10000, and printing a result of the sum.
Of course, there ain't any variable type that can hold a integer which length is 10000 in C.
So, I made the program by utilizing the simple additions' calculating logic that all we learn in a school when we were young. And also, I just should use strings to get those gigantic numbers.
But some results were starting with zero. I knew why did the zero appeared there, but I did prefer to have a result that is like "1234", not "01234". By the way, all other stuffs were perfect.
I needed a function that gets input as string, and erases a single zero starts with a string if it exists.
And could you make it instead of me, please? You should probably consider that the strings we will deal with can have such a length that is smaller or same with 10000.
Maybe this:
char * f( char * str )
{
while ( *str == '0' && str[1] )
str++; // skips all zero-s when it is not last character in string
return str;
}

Passing string as a case condition [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In C language, is it possible to pass string as a case condition in switch case?
If possible, can AI (Artificial Intelligence) be achieved?
Is it possible to pass string as a case condition in switch case?
No - the switch statement only operates on integer values; case labels must be constant integral expressions. You'd have to map the string onto an integer value, either by using a hash function or a lookup table or something.
#define MAX_LEN 80 // or however long you need
#define HELLO_STRING some-integer-value
#define GOODBYE_STRING some-other-integer-value
#define NO_MAPPING 0
int mapToInteger( const char * str )
{
int mapValue = NO_MAPPING;
/**
* logic to map string to integer
*/
return mapValue;
}
int main( void )
{
char inputString[MAX_LEN];
...
while ( fgets( inputString, sizeof inputString, stdin ) )
{
switch( mapToInteger( inputString ) )
{
case HELLO_STRING:
process_hello();
break;
case GOODBYE_STRING:
process_goodbye();
break;
default:
case NO_MAPPING:
i_dont_understand();
break;
}
}
}
Will case or whitespace matter? In other words, should "THIS IS A TEST" and "This is a test" and "tHiS iS a TeSt" all give the same result? If so, then your mapToInteger function (or whatever you decide to call it) will have to take all that into account.
If possible, can AI (Artificial Intelligence) be achieved?
This is the programming equivalent of asking, "if I can use a hammer to nail two pieces of wood together, can I build an apartment complex?" Yeah, sure, but you need to do a bunch of other stuff as well.
The short answer is that a switch in C only accepts integer values, or something easy to cast to an integer (like a character).
There are workarounds tough, like using a hash function or using a series of “if”.
Concerning Artificial Intelligence, this is a vast field, that cannot be addressed with a simple switch. At least for a good result. You can have a look at expert systems as a start.

Printing numbers as English words in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have this code that will print numbers from 0 to 9 in english words (like one for 1, two for 2, etc.). What if I wanted to print 374? Or something much larger, like 7549846451?
#include <stdio.h>
int main()
{
double sum;
if(scanf("%1f",&num)!=0)
{
if(num=(int)num)
{
switch((int)sum)
{
case 0:printf("zero\n");break;
case 1:printf("one\n");break;
case 2:printf("two\n");break;
case 3:printf("three\n");break;
case 4:printf("four\n");break;
case 5:printf("five\n");break;
case 6:printf("six\n");break;
case 7:printf("seven\n");break;
case 8:printf("eight\n");break;
case 9:printf("nine\n");break;
default:printf("not a digit"); break;
}
}else
{
printf("Invalid")
return 0;
}
}
return 0;
}
This is a good start, but it would take a lot more to complete your program:
Start by expanding your code to printing numbers 10..99. There would be a special case for 11..19, but after that it's pretty regular. The lower 20 can be addressed with a lookup table. In fact, making a look-up table for the whole range wouldn't be too bad, either.
With a routine that writes out numbers 0..99 in hand you can expand into hundreds by looking at the third digit the right, writing it out, adding "hundred", and proceeding to writing out the number 0..99
Now that you have a routine for writing out three-digit numbers all you need is to split your number into groups of tree, calling this routine for non-zero groups, and adding "billion", "million", and "thousand" corresponding to the rank of the group.
Here you have the solution to your problem. It is even the same example as you have pasted here, so if you have read the comments below, you'd have seen the comment form Bheema in which he posted the whole code for it.
Also, you can try writing your own code, it's not that hard. dasblinkenlight gave you instructions how to do it.

Converting char integer representations to binary [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a char array composed of elements 5 3. The array is used to represent number 53. What should be the approach to convert this number of three chars to its binary equivalent? I am implementing this in C, later on it will need to be rewritten in assembly. The solution I seek should be purely low stuff work without any helper libraries.
I am basically stuck with an idea to convert separately 5 and 4 (via mapping 5 and 4 to their ascii equivalents). Yet the idea would not work for sure. I have another idea to convert char '5' to int 5 by right shifting the byte by 4. Same with 4. Then multiply 5 by 10 and add 4, and then use division by two algorithm to find remainder and compose the binary number.
In C:
int asciToInteger(char *c)
{
int result = 0;
while (*c)
{
result *= 10;
result += (*c - '0');
c++;
}
return result;
}
Assumes input is valid.
You can get a head start on the assembly language version by compiling with certain switches which will output as ... assembly language! For example in GNU C: gcc -S -c ascii2int.c.

Resources