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
Related
I just started programming in C, and while practicing with for loops, I came up with the following piece of code:
#include <stdio.h>
int main()
{
int x;
for (x=0;x=10;x=x+1)
printf("%d\n",x);
return 0;
}
When I run the code, I fall into an infinite loop. In my C manual it says that the condition x =10 is always true, but I can't get my head around it. If I give the variable x a value of 0 at the beginning, should the for loop not even start, or when the value of x reaches 10, shouldn't the loop stop?
Thanks in advance!
The condition part of your for loop is wrong. What you are doing is :
for (x = 0; x = 10; x = x +1) {
// Operations
}
The condition you have got here is x = 10 which is an affectation. So x = 10 will return 10, which also means true. Your for loop is equivalent to :
for (x = 0; true; x = x + 1) {
// Operations
}
This is why you have got an infinite loop, you should replace the affectation operator = by the comparason one with two equals sign ==. This means the for will loop while x is equals to 10.
EDIT : As Virgile mentioned in comments, for the second for loop, x will go from 0 to INT_MAX, then the behavior is undefined. So, your code is more likely to look like :
for (x = 0; true; x = 10) {
// Operations
}
When entering a for loop, the initialization part is performed first. So after the loop initialization x is 0.
Before entering the body of the loop, even the first time, the condition is checked. The "condition" in this case does not compare x to 10 but sets it to 10 since you are using = instead of ==.
Since an assignment as an expression has the value of the variable after assignment, the conditional expression has a value of 10 since that is what was assigned to x. Because this value is non-zero, it evaluates to true, and always will.
The problem here is, Take a close look on the condition part(2), in this what x=10, means is it is just assigning the value 10 to x, and it returns "True" always, so no problem what you have incrementing, it comes to 10 always, Thus infinite loop.
What you are trying to do is, you are implicitly converting int to bool in this line:
for (x=0;x=10;x=x+1)
^^^^
here, x=10; results true
So, it prints 10 everytime as you are using the = assignment operator.
for(int x=0;true;x=x+1)
What you could do to maintain the loop?
Use relational operators:
for (x=0;x!=10;x=x+1)
for (x=0;x==10;x=x+1)
for (x=0;x<10;x=x+1)
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.
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).
Why the loop stops when i = -1?
for (i = len; i--;)
Full code is here http://rosettacode.org/wiki/Longest_increasing_subsequence#C .
Thx!!
The loop stops when the value of i-- is 0. Since i-- returns the value before the decrement, when i-- is 0, i is -1.
I don't see an answer worthy of being right, though Joachim Isaksson's comment is a concise explanation.
The loop stops when it evaluates a value of 0 or false.
The i-- is what's throwing you off. That's "post-decrement", i.e. the operator returns the current value of i (in this case, for the loop to evaluate), and immediately thereafter, decrements the current value. Pseudocode for postdecrement follows:
int retval = i;
i = i - 1;
return retval;
(Based on Eric Lippert's comments, technically, the compiler could do postdecrement as i = i - 1; return i + 1;. The point is that the value emitted by the operator is no longer the value of i.)
(as opposed to predecrement, which in pseudocode is simply):
i = i - 1;
return i;
So when the loop is evaluating i, it sees 0 so exits, but immediately after evaluating the operator has decremented i to -1.
So, to answer your question:
The loop doesn't stop when i = -1. It stops when i = 0, but then i is decremented to -1.
Your loop stops when the expression i-- becomes 0 because any non-zero value in C is treated as true and a zero as false.
At each iteration i is checked for true or false and then decremented .
for (i = len; i--;)
here i-- is the exit condition. when i-- is false which is 0 the loop will exit.
since i-- is post decreament i value is used for condition checking. so when
i=0;
loop exits after that i=i-1 is executed as part of post decrement so
i=-1;
when loop exits since first i's value is used after that it is decremented
FOR loops are composed of 3 parts:
for ( [Initialization] ; [Exit Condition] ; [Cycle Update] )
[Initialization] is used to assign a value to the loop index before the first iteration
[Exit Condition] is a boolean expression evaluated before each iteration. If it is true another iteration is executed, otherwise the FOR loop ends
[Cycle Update] is the instruction used to update the loop index at each iteration
a classical FOR statement looks like this:
FOR(I = len ; I > END_VALUE ; I--)
What is probably missing in your code is the exit condition, so the cycle update part is interpreted as an exit condition and consequently treated as a boolean expression. When the integer becomes 0 its interpreted boolean value corresponds to FALSE and the loop is ended. Any non-zero value is instead interpreted as a TRUE boolean and allows the execution of another iteration.
When a boolean value is needed, 0 is same as false. Anything other than 0 is true. So, it must stop when i is 0, not -1. You are seeing the value of i to be -1 because of the post-decrement operator.
#include <stdio.h>
int main()
{
int x = 0;
if (x++)
printf("true\n");
else if (x == 1)
printf("false\n");
return 0;
}
Output:
false
Why is the output false?
x++ is post increment; this means that the value of x is used then it is incremented.
If it is so, then x=0 should be used and the answer should be true.
In C, 0 is treated as false. In x++, the value of x, i.e, 0 is used in the expression and it becomes
if(0) // It is false
printf("true\n");
The body of if doesn't get executed. After that x is now 1. Now the condition in else if, i.e, x == 1 is checked. since x is 1 , this condition evaluates to true and hence its body gets executed and prints "false".
Post increment means that it returns the current value (in this case for the purpose of the if) and increments it afterwards. It is equivalent to
if(x) {
x++;
// ...
} else {
x++;
// ...
}
0 is equivalent to false in C. As you are using post-increment operator, condition is evaluated before increment so x is false and printf("true\n"); is never executed. Then goes to else and succeeds evaluating x == 1, then prints false.
As a good practice, try to avoid assignations in condition sentences.
0 is false in C. You're using the post-increment operator.
You yourself wrote: "x++ is post increment, this means that the value of x is used then it is incremented"
Consider what that means:
x is 0
The expression is evaluated, 0 is false, so the expression is false.
The post increment happens, changing x from 0 to 1. (After the expression was evaluated)
My opinion is that a better response to the relation between 'if' statement and the post increment operator '++' requires the expansion of your C-code into Assembly.
Trying to figure it out under the constricting logic of blocks of the "if ... else" statement, of high level languages, might be misleading because the flow control is read in different terms.
Consider that the pre and the post operators rely on the "change-then-use" and on the
"use-then-change" rules respectively, where 'change' is meant by 'increment' and 'use' by the 'comparison'.
So your input C-code basically turns into this raw pseudo-assembly:
; evaluating the first condition
mov x,0 // set x = 0
cmp x,0 // use (for comparison)
inc x // then change (now x is 1)
je print1
; evaluating the second condition
mov eax,1
cmp eax,x // evaluates to true
je print2
print1:
printf("true\n");
print2:
printf("false\n");
Take care that compilers might not put the inc instruction at the same position, that is, at the top or at the bottom of the labelled block of instructions.
Hope it helps!
I believe this simply could fix the error
#include <stdio.h>
int main()
{
int x = 0;
if (++x)
printf("true\n");
else if (x == 1)
printf("false\n");
return 0;
}