I'm trying to write simple program using c to compute the intersection between two strings using Bitwise AND operator Like :
char x[]="abcdefghijklmnopqrstuvwxyz";
char y[]="abcdefghijklmnopqrstuvwxyz";
int i,sum=0;
const int size = 26;
for(i=0;i<size;i++)
{
if(x[i]&y[i]==y[i]){
printf("%c",y[i]);
sum++;
}
}
printf("\n%d\n",sum);
After executing code i found the result :
acegikmoqsuw
13
what's the problem with my code or what's the reason for that ?
You should take care of operand precedence in the if:
char x[]="abcdefghijklmnopqrstuvwxyz";
char y[]="abcdefghijklmnopqrstuvwxyz";
int i,sum=0;
const int size = 26;
for(i=0;i<size;i++)
{
if((x[i] & y[i]) == y[i])
{
printf("%c",y[i]);
sum++;
}
}
printf("\n%d\n",sum);
Your code isn't strictly correct; if every x[i] were 0xff then it'd think that every character matched. All you're going to detect is anywhere that the relevant x has a 0 that the relevant y does not.
If the requirement is to use &, for whatever academic purpose, then run the test in both directions:
if( (x[i]&y[i])==y[i] && (x[i]&y[i])==x[i] )
i.e. if there are no bits set in y that are not also set in x and there are no bits set in x that are not also set in y then the two must have the same bit pattern.
Though, obviously:
if( x[i]==y[i] )
... is the intended means of testing for equality in C.
Your problem lies in the evaluation of the if statement
if(x[i]&y[i]==y[i])
the == operator has greater precedence than the & operator.
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
Try replacing it with this:
if( (x[i] & y[1]) == y[1] )
Related
me again ... Sorry for asking maybe a little bit stupid questions but i am a starter and i really want to learn coding .. So i got a problem to realize why those are always true ? Its something with the operators or again C behavior is undefined. ?
int x;
int b;
b = 1 < x < 10;
printf("%d%d",b);
char c = 'z';
(c==' ') || (c='\t') || (c=='\n');
printf("%c",c);
Why those are always true ? Its because of ASCII code or what ?
Result of comparison of constant 10 with boolean expression is always true
You can see here a table for the C Operator Precedences
it could be read like this:
b = ((1 < x) < 10);
being that in languages such as C, relational operators return the integers 0 or 1, where 0 stands for false and any non-zero value stands for true.
so the value stored in b is 1 (true)
Also:
you're not initializing x, it should have trash info (probably != false)
and in your second code, you're allocating instead of comparing, (c='\t') is this on purpose? That's the reason it's printing a 'tab'.
In your first block of code, there are several problems:
x is uninitialized (you did not give it a value)
1 < x < 10 is not valid C
your printf statement expects 2 integer values to accompany the "%d%d", but you are only passing 1
I think this is what you want:
int x = <some valid value>;
int b;
b = ((1 < x) && (x < 10)); // expression is true if x is between [2..9]
printf("%d",b);
This line
(c==' ') || (c='\t') || (c=='\n');
Should be
(c==' ') || (c=='\t') || (c=='\n');
Note the double equals when comparing to \t (the tab character). Otherwise, you wind up assigning a tab char to c.
i'am learning C,and after learning the array,i want to try something,but here comes the confusion.
i try to print a-z but there are something more("{|") been printed.and i am confused with it.
int count;
char ph[26];
char x;
for(count = 0, x= 'a'; count < 26 , ph[count] = x; count++ , x++)
printf("%c",ph[count]);
I expect the output to be a-z, but the actual output is a-|.
Thank you and I realize that what matters is the comma operator.
The problem is that the stopping conditional expression
count < 26, ph[count] = x
has the value x, i.e. count probably runs past 25. This is how the expression separator operator , behaves.
If this means that you end up with an out of bounds read of ph (which you do on ASCII encoded platforms), the behaviour of your code is undefined.
The way you have written the loop is unnecessarily obfuscating, but if you want to stick to a similar way then writing
count < 26 && ph[count] = x
is the fix. Finally note that ASCII is not the only encoding supported by C, so even when you do get the program working on your platform, you have not written it in portable C.
This for loop
for(count = 0, x= 'a'; count < 26 , ph[count] = x; count++ , x++)
printf("%c",ph[count]);
is incorrect.
In the condition of the loop
count < 26 , ph[count] = x
there is used the comma operator. The value of the operator is the value of its second operand that is the value of the assignment ph[count] = x. The first operand count < 26 is just ignored.
As a result the loop has undefined behavior.
Rewrite the loop the following way
for(count = 0; count < 26; count++ )
printf( "%c", ph[count] = 'a' + count );
What I need to do is read a file which contains equations. I need to take the derivative of each equation and then write those derivative equations in a different .txt file. I've read all the equations into an array of character arrays and now I don't know what to do once I've stored them into the array. I really don't need help writing the equations into another file; I know I can figure that out.
What I need help on is finding a way to taking the derivative of the functions. The type of equations that are going to be read are not that complicated; they're going to be polynomials that don't need the chain rule or quotient rule. There will be, however, sin x, cos x and tan x. Some sample equations that would be read are.
-2x^2+2x-3
-2x+sinx-3
-x+sin2x-tanx
The trig functions will not have parenthesis and the variable will always be "x".
I just need a push in the right direction, please.
What you're really asking for is a parser.
A parser is basically a set of rules to read those equations and change/read (parse) each of them.
I'd try to iterate over each line of the file, and differentiate it considering you have a specific character set (i.e ^ means power, x is the parameter, etc.);
For example, some pseudo code:
Open the file.
While there's lines to read:
Read a line -
Seperate it by the operands (+,-,/,*)
For each part:
Find the power of x,
Reduce it by one,
...(derivating rules) // no way around, you have to implement each function if you want this to work as others mentioned in the comments.
Reconnect the parts into a string,
Add it to a list.
Print each element of the list.
If you need help translating that into C, just ask for it; I'll happily help you.
What you need to do, by the looks of things, is separate the expression into individual terms so that you can find the derivative of each in turn.
You can define a term as the largest sequence of characters not containing term separators such as (in your examples) + and -.
Hence the terms for your examples are:
-2x^2+2x-3 => 2x^2 2x 3
-2x+sinx-3 => 2x sinx 3
-x+sin2x-tanx => x sin2x tanx
For each term, you then need to evaluate the form of the term. The form will dictate how you create the derivative.
For example, you can detect if it contains a trigonometric function of the form [n]sin[m]x where n and m are optional numbers. To simplify things, you could add in those terms if they're not there, such as sinx becoming 1sin1x (I'll call this the full-form of the term). Being able to assume all subterms are present will greatly ease the derivative calculation.
Let's say the term is sin4x. Expanding that will give you 1sin4x which you can then split into term-multiplier 1, function sin and x-multiplier 4. Then using standard derivative knowledge nsinmx => (n*m)cosmx, this would become 4cos(4x) and that term would be done.
If it doesn't contain a trigonometric function, you can use the same full-form trick to cover all of the power/constant expressions with the following rules in turn:
if it's a constant (all numeric), append x^0 (multiply by 1).
if it ends with x, append ^1, so 4x becomes 4x^1.
if it starts with x, prefix it with 1, so x^3 becomes 1x^3.
Once that's done, you will have a full-form of ax^b and you can then create the derivative (ab)x^(b-1) and post-process it:
if the bit after x is ^0, remove the whole x^0.
if the bit after x is ^1, remove the ^1.
if the bit before the x is 1, remove it.
if the bit before the x is 0, remove the entire term (and preceding term separator, if any).
So, taking a complex combination of your test data:
-2x^2 + 5x + 4sin3x - 3
which can be treated as:
0 - 2x^2 + 5x + 4sin3x - 3
The following actions happen to each term:
0 [0x^1] (derives as) 0, remove it.
2x^2 [2x^2] (derives as) (2*2)x^(2-1) => 4x^1 => 4x
5x [5x^1] (derives as) (5x1)x^(1-1) => 5x^0 => 5
4sin3x [4sin3x] (derives as) 12cos3x
3 [3x^0] (derives as) 0, remove it and preceding '-'
Thus you end up with - 4x + 5 + 12cos3x which, although my calculus education is some thirty years in the past (and I don't think I've used it since, though I will no doubt be using it next year when my eldest hits secondary school), Wolfram Alpha appears to agree with me :-)
This function will parse the text, cut it in to different parts identified by type[i], stores in a structure. It recognizes x, +, -, and numbers. It can be expand it to include other operators etc.
#define maxlen 50
#define idx 0 //X variable
#define idnumber 1 //number
#define idplus 2 //+ sign
#define idminus 3 //- sign
struct foo
{
int type[10];//each type can be a number (idnum), +, -, etc.
int num[10];//if type[i] is number then num[i] identifies that number
int count;//total number of parts
};
void parse_one_line(struct foo *v, const char *s)
{
char buf[maxlen];
memset(buf, 0, maxlen);
int j = 0;
//remove white spaces
for (int i = 0, len = strlen(s); i < len; i++)
{
if (s[i] == ' ') continue;
buf[j] = s[i];
j++;
}
char part[maxlen];
v->count = 0;
for (int i = 0, len = strlen(buf); i < len; i++)
{
char c = buf[i];
if (c == 'x')
{
v->type[v->count] = idx;
v->count++;
}
else if (c == '+')
{
v->type[v->count] = idplus;
v->count++;
}
else if (c == '-')
{
v->type[v->count] = idminus;
v->count++;
}
else if (c >= '0' && c <= '9')
{
int j = 0;
memset(part, 0, maxlen);
for (; i < len; i++)
{
c = buf[i];
if (c >= '0' && c <= '9')
{
part[j] = c;
j++;
}
else
{
break;
}
}
i--;
v->num[v->count] = atoi(part);
v->type[v->count] = idnumber;
v->count++;
}
}
for (int i = 0; i < v->count; i++)
{
switch (v->type[i])
{
case idnumber: printf("%d", v->num[i]); break;
case idx: printf("X"); break;
case idplus: printf("+"); break;
case idminus: printf("-"); break;
default:break;
}
}
printf("\n");
}
int main()
{
struct foo st;
parse_one_line(&st, "-23x + 2 + 2x - 3");
return 0;
}
How can I convert the following code to a single line?
int *i;
i = some_func_ret_int_ptr();
if(!i)
{
// Do something
}
// Will use 'i' later
I want to do something like:
if((i=some_func_ret_int_ptr) && !i)
{
// Do something
}
// Will use 'i' later
But I am wasting one comparison here. Is there a better way to do it?
All I want is assignment and comparison in the if and compare only i.
With C, this is as far as you can golf it:
int *i;
if(!(i = some_func_ret_int_ptr()))
{
// do something
}
// Will use i later
In addition to what is suggested in other answers, you can also do it as
if (i = some_func_ret_int_ptr(), !i)
{
// Do something
}
It is a literal implementation of what you had originally, with the statement sequence replaced with an expression sequence separated by the , operator.
It does not make much practical sense, though.
You can do
if(!(i = some_func_ret_int_ptr()))
{
...
}
What happens in this code, in order, is:
The return value of some_func_ret_int_ptr() is assigned to i
The statement !i is checked
If i == 0 what's inside the if gets executed, otherwise it will not
Clean and readable:
int * i = some_func_ret_int_ptr();
if (!i) { /* ... */ }
An option not mentioned yet is:
if ( NULL != (i = some_func()) )
Using the explicit comparison against NULL makes it very easy to read the intent of this code. Especially considering that your function probably won't have ret_int_ptr in its name.
Using the #include <ctype.h> standard library, to get the toupper(char) function, we can write the following function:
void StringToUppercase(char* str)
{
for (int i=0; (str[i] = toupper(str[i])) != 0; i++); // No for-loop body!
// The expression "(str[i] = toupper(str[i]))" executes first and then returns str[i]
}
so that the statement (str[i] = toupper(str[i])) != 0; both assigns a char and checks to see if it is '\0' or not.
The way this works is that part of the C language specifies that assignment expressions have the value of the lefthand expressions after the assignment. For example, with ints, consider the following code snippet:
int x = 5;
int y = x = 8;
// Assignment operators (= += <<=) have right-to-left associativity.
// The expression `(x=8)` returns the value 8, after it has been executed
int z = x != y; // Comparisons have greater (tighter) precedence than assignment
printf("(x, y, z) = (%d, %d, %d)\n", x, y, z); // prints (8, 8, 0)
Same as M.M's answer, but I would go with:
if ((i = some_func_ret_int_ptr()) != NULL)
As it makes the execution order clearer.
This is the line of code in C.
The condition of loop here is ++i.
So how does compiler decide which condition to consider because here other two appear as conditions?
char i=0;
for(i<=5&&i>-1;++i;i>0)
printf("%d",i);
output
1234..127-128-127....-2-1
The for statement works like this:
for (X; Y; Z)
{
...
}
translates to
X;
while (Y)
{
...
Z;
}
So your code changes from:
char i=0;
for(i<=5&&i>-1;++i;i>0)
printf("%d",i);
to:
char i = 0;
i<=5 && i>-1; // X
while (++i) // Y
{
printf("%d", i);
i > 0; // Z
}
As you can see, lines marked with X and Z are completely useless. Therefore:
char i = 0;
while (++i)
printf("%d", i);
This means it will print from 1 up to whenever result of ++i is zero.
If char in your compiler is signed, then the behavior is left to implementation, even though most likely it will overflow to a negative value and work its way up to zero.
If char is positive, this will print positive values up to where it overflows back to 0.
It doesn't. It runs the first part and i gets set to any side effect of this, then it terminates when the second part is false, in this case when i is 0, then on every loop it runs the 3rd part.
SO the compiler essentially rewrites this as:
char i=0;
i<=5&&i>-1;
do {
printf("%d",i);
i>0;
} while ( (++i) != 0)
hint: remember char is signed and twos complement, so i will go 1,2,3....128, -127,-126.... 0
the loop termination condition here is ++i. There is no mystery about it. The loop will stop when i hits 0 (because the it will be 'false')