int i=0;
if(4||1&&++i)
{
printf("%d",i);
}
O/p=0
But according to me o/p should be 1 due to preincrement....plz explain
When we use || it will check if first condition is false then it will go to second condition and so on, however the moment it finds a true condition it will return 1.
In this case 4 is true so it will not evaluate further statements here 1 && ++i and it will directly go to print("%d",i);
As you have initialize i to 0 it will print the value 0.
If you want if condition to evaluate 1 && ++i also, then in place of || (OR) use &&(AND).
Related
So I saw this in my text book and I cannot understand how it works.
x=0;
int i = 0;
int n;
while(!x && i < n){
if(array[i]==target)
x=1;
else
++i;
}
what I don't understand is how "!x" works in loop's condition.
what I understand is this loop keeps running until it runs n times or when array[i]==target, which will change the value of x = 0 to x = 1 and stop the loop.
what I tried:
I tried replacing !x to x==0 and it did the same job.
The short answer here is that it does not matter what !x is because it is surrounded with undefined behavior completely nullifying its effect.
In the statement
While(condition) {...}
condition must resolve to either true or false, and must therefore be logical expression.
Given:
int x=0;//This answer assumes 'int' here as not specified in OP
int i = 0;
int n;
while(!x && i <n)
Because x is initialized as 0, equivalent to false the expression !x resolves to true, satisfying part of the condition.
Because n is not initialized however, the condition (!x && i <n) invokes undefined behavior, making the results of the overall condition unknown at the time of first entry, i.e. it can be either true or false. Further more, n does is never modified within {...}, so if the initial path happens to enter the brackets, the condition will change only due to changes in i. But again, because the value of n is not known, only undefined behavior will occur.
I don't know what language this is but !someVar is typically shorthand syntax for "variable is false", or another way of writing someVar == false. And in binary 0 is false and 1 is true. In the C language, 0 is false and anything not 0 is true. Therefore, in your loop, while !x is shorthand syntax for while x == false or while x == 0. Again, generally speaking since we don't know the language.
While(!x) means if x is a condition then we go into the while loop, only if the condition does not satisfy.Here in your code you have assigned x as zero,so !x means 1 because '!' Basically means opposite if x =0 then !x =1, if x=1 then !x=0 (all numbers greater than 1 are also considered as 1 only) so while(1 && i<n) is what happening here in the next step.If i<n is true then you will enter into the loop. If i<n is false the you won't enter the loop.
while(!x)
{
intructions;
}
means that your instructions will only keep running over and over again if x is false or equals 0 and will stop executing instructions once x becomes true or different from 0
#include <stdio.h>
int main()
{
int i=0;
while(i++,i<=8);
printf("%d\n",i);
return 0;
}
Why is the increment of i done after the comparison in each test case?
i <= 8 succeeds for the last time when i = 8.
In the last iteration, i++ is executed, then i <= 8 fails because i = 9.
Note that the , is a sequence point, so i++ is absolutely guaranteed to be executed before i <= 8. Not so for similar constructs.
It's not. Your loop condition is i <= 8, it is first non-true when i reaches 9 (you're incrementing i by 1 each time, so it will be exactly 9). That is why it prints 9.
To reach to the print() statement, while loop must end. The terminating condition, controlling expression should evaluate to false (or, in other words, until the controlling expression compares equal to 0), i.e., it will be false only when i <= 8; evaluates to false. For a value of i as 9, that happens.
Next line, the value of i, gets printed. So, you see 9.
Increment of i is not done after the comparison in each test case. i++ is executed first and after that the comparison is done.
This is because when expressions are separated using commas in C, the expressions are evaluated from left to right and the value of the last expression becomes the value of the total comma separated expression.
So the value of
i++,i<=8
is actually the value of i<=8 and that comparison is done only after i++ is executed.
So the while loop here
int i=0;
while(i++,i<=8);
is equivalent to
for(i=1; i<=8; i++);
Hence the control exits the loop only when i is greater than 8. Since i is incremented by 1 on each iteration, this means that the loop is over when i becomes 9.
You started i = 0 and using while ( i++, i<=8 ) loop you incremented it's value until 8 and when it's increased one more time i = 9 , then loop condition became false and breaks the loop with i = 9. And that's why now, when you print i's value, it gave you 9.
This question already has answers here:
How is i==(20||10) evaluated?
(2 answers)
Closed 7 years ago.
#include <stdio.h>
int main(void)
{
int i=10;
if(i==20 || 30)
printf("True");
else
printf("False");
return 0;
}
//Gives output:True
//Please tell me how this if loop is getting evaluated
There is no loop here..
Just one condition check, which has the following condition.
if(i==20 || 30)
First, you should know, any non-zero value is taken as True in a condition check.
So, first i is checked with the value 20, if thats true then True is printed, else it checks the next condition as there is an OR inbetween. SInce the next condition is non-zero which is always true, therefore it goes inside and prints True.
NOTE: This program will always print True, as the next condition is always true, and there is an OR in between which needs only one of the conditions to be true.
I have a feeling you want to check "if i is 20 or 30". The syntax for that is "if ( i is 20 ) or (i is 30)". The translation of that logic into code is:
if ( i == 20 || i == 30 )
When you use
if ( i == 20 || 30 )
it is translated as:
if ( (i == 20) || 30 )
regardless of what (i == 20) evaluates to, the conditional expression will always evaluate to "true" since 30 is a non-zero value.
Your if statement as two conditions
First is (i==20) and second is 30
The second conditions is 30 which is always true.
For "OR" operation any one true is enough to execute the if statements
So the statements under if are executecd
In your code:
i==20 give result false because i=10
i==20 || 30 equals to false || 30 give results true because 30 (or non-zero values) equal to true in condition check.
It should be:
if((i==20) || (i==30))
The expression if(i==20 || 30) is turning out to be true(non zero) hence you are seeing the output as true. The expression will be evaluated according to the precedence at which the operators get evaluated. == has higher precedence than || hence i==20 will be evaluated first and the result becomes as follows
if( true || 30 )
Now the operator is || the Left operand will be checked first which is true and control enters if block and prints true. This is called short circuit evaluation. If we have logical || operator, first the Left operand will be evaluated. If the left operand is true compiler wont evaluate right operand.
can anyone explain the working of the for loop in the following code:
#include<stdio.h>
#include<conio.h>
int main()
{
char i=0;
for(i<=5&&i>=-1;++i;i>0)
printf("%d\n",i);
getch();
}
Let's break the for statement down, we have three phases, the initialiser, the test, and the modifier:
for(<Initialiser>; <Test>; <Modifier>)
<content>;
In your case:
for(i<=5&&i>=-1;++i;i>0)
// initialiser: i<=5&&i>=-1;
// test: ++i;
// modifier: i>0
The initialiser is done first. Here no assignment is done. Two boolean expressions (denoted by the >= and <= operators are compared in a logical &&. The whole initialiser returns a boolean value but it doesn't do anything. It could be left as a blank ; and there would be no change.
The test uses the pre-increment operator and so returns the result of i+1. If this result is ever 0 it evaluates as false and the loop will terminate. For any non-zero value it evaluates to true and continues. This is often used when i is initialised to a value less than zero and so the test will increment i until i+1 results in a zero, at which point the loop terminates.
Finally we have the modifier, which in this case simply uses the > operator to evaluate to a boolean value. No assignment is done here either.
The fact is that you've gotten the test and the modifier confused and put them in the wrong positions but before we sort that out let's see how it would work…
We begin with:
char i = 0;
…and for all intents and purposes this does the same thing as our for loops initialiser would do in normal circumstances. The next thing to be evaluated is the for loop's initialiser:
i<=5 && i>=-1;
Because i is 0 it is less-than-or-equal-to 5 and it is greater-than-or-equal-to -1. This expression evaluates to 1 but nothing is done with that value. All we've done is waste a bit of time with an evaluation.
Next up is the modifier to test whether or not the for loop's inner block should be executed:
++i;
This evaluates to 1 and also assigns that value to i. Now, as it's evaluated to a non-zero number, the loop executes:
printf("%d\n",i);
And the digit 1 is printed to the screen... Now it's the modifier that gets executed:
i>0
Well, i is 1 so that is greater-than 0. This evaluates to 1 (or true). Either way, this is ignored. The purpose of the modifier isn't to test or check anything. It's there so that you can change the state of the program each time the for loop iterates. Either way, the loop repeats and it will do this for a very long time. Why? Because ++i is going to evaluate to a non-zero number for a while. Whether or not it will ever terminate depends on how your system deals with integer overflows.
This is what you meant to do:
#include<stdio.h>
#include<conio.h>
int main()
{
for(char i=0; i<=5&&i>=-1; ++i)
printf("%d\n",i);
}
Do you see the difference? Our initialiser now starts the loop with the state of i as zero. We then test if it's within the bounds of -1 to 5 and each time we iterate we increment i by 1. This loop will output:
0
1
2
3
4
5
This snippet:
for(i<=5&&i>=-1;++i;i>0)
printf("%d\n",i);
Does the same as this:
i<=5 && i>=-1; //statement with no effect
while(++i)
{
printf("%d\n",i);
i>0; //statement with no effect
}
So, it's going to print i until ++i evaluates to 0. This will happen after i overflows and becomes negative, then incrementing towards 0. That will take 255 iterations to happen, since chars can store up to 256 different values.
for ( variable initialization; condition; variable update ) {
}
the variable initialization phase is done only once when the for loop starts.
the condition is checked everytime before running code inside the loop. if the condition is false then the loop is exited.
the variable update is done after the first iteration, from the second iteration it is done before the condition check.
I am experimenting about what can be put into a for loop declaration in C and how it can be used. I tried the following:
#include <stdio.h>
int stupid(int a)
{
if(a == 3)
return 1;
else
return 3;
}
int main(void)
{
int i, j;
for(i=0; stupid(i)==3,i<10; i++)
printf("%d\n", i);
return 0;
}
When I run the program it just prints the number from 1 to 10, and if I use && instead of comma between the stupid(i)==3 and i<10, then the program just prints the numbers up to 3. Why?
I don't really understand how this works and I was expecting the loop to pass all numbers and "skip" 3, but continue up to 10 and that's not really happening. Why does this happen? Is there some site where this is more clearly explained?
The second clause in the for loop (in your case stupid(i)==3,i<10) is a conditional that is evaluated prior to each entry of the loop body. If it evaluates to true then the loop body is executed. If it evaluates to false then the loop ends and execution continues after the loop body.
With the comma (stupid(i)==3,i<10), the code evaluates stupid(i)==3, forgets the result, and then evaluates i<10, and uses that result for the loop condition. So you get the numbers from 0 to 9.
stupid(i)==3 && i<10 will evaluate to true only if both parts of the expression are true, so when i=3, stupid(i)==3 is false, and the loop exits.
The comma operator evaluates the part before the comma, discards the result, evaluates the part after the comma, and returns that. So in your for loop the part after the comma is i < 10 and this is what is returned as condition for the for loop. That is why it prints the numbers 1 to 10 if you have the comma operator in it.
If you put the && operator in it, it means that both conditions before and after the && have to be met. Otherwise the loop terminates. So if i == 3 the left part evaluates to false and your loop ends.
The comma operator evaluates both, but then overall returns the value of its second operand. Since stupid() doesn't have any side effects, that means nothing much of use really happens here and you're overall just checking to see if i<10.
When you change it to && then both functions must return true (non-zero) for the iteration to continue. On the first pass through, on which the statement evaluates to false, the for loop halts and control continues past it.
The for loop will only continue if the conditions are met. If you place an if statement within the for loop to verify that stupid(i) is equal to three, the for loop will continue.
Using the , operator expands to each line being run. The last line is expected to return a Boolean expression that indicates whether the next iteration should be executed.
In this case, while stupid() does get called, it only checks the return value from the expression i < 10 to decide further execution.
In the for loop, there are three expressions needed, and they are separated by semicolons.
The first is an initializer, and it is run one time before the loop starts. It usually initializes the loop variables.
The second is a condition, and it is run right after the initializer and then before each subsequent iteration. If it is true, the loop statements are run. If it is false, the loop is over.
The third is an expression that is run right after each iteration and right before the condition is checked before the next iteration. It usually progresses the loop by changing the loop variable.
Your condition stupid(i)==3,i<10 uses the comma operator. The comma operator runs each side, but it returns only the value of the right hand side. The value of stupid(i)==3 is completely ignored. The condition stupid(i)==3 && i<10 is true only if both sides are true.
Remember, when the condition is false, the loop is over -- the iteration is not just skipped, the entire loop is over. To get what you want, use
for(i=0; i < 10; ++i) {
if (stupid(i)==3) {
printf("%d\n",i);
}
}
This will go through 0-9, but skip the code if stupid(i) is not 3.
Use:
int main(void)
{
int i,j;
for(i=0; i<10; i++, i+=i == 3)
printf("%d\n", i);
return 0;
}
The limit condition on can only terminate the loop when the condition comes true, not skip iterations. If you want to skip some value, you have to do it at the counting part of for(), or do this with if().
i+=i==3 adds 1 to i when i becomes 3, as i==3 evaluates to 1 if the condition is met and to 0 otherwise (and adding 0 simply does not make any difference).