Infinite Loop While Producing a Random 0/1 Output - loops

Entry level comp sci major here.. I'm certain this question likely has an obvious answer, but I simply can't figure out why the following code produces an infinite loop and it's driving me insane. I understand that Math.random() returns a double value which when multiplied by 10 moves the decimal once to the right and the (int) typecasts the double data type to an integer by truncating the rest of the digits after the decimal point.. but then why on earth is the following code producing an infinite loop one of the boolean expressions will eventually produce a true value?
Now if I use && instead of || in the loop, it will work just fine because the && checks both expressions for a true yield prior to determining the outcome of the entire expression. Ah.. help..
int x;
do {
x = (int)(Math.random() * 10);
}
while (x != 1 || x != 0);

It is actually quite simple: Your variable 'x' can not be two different integer values. It does not matter if your variable is 0,1,2,3,4,5,6,7,8 or 9. Your while condition will always be true and therefor your loop will always run forever.
e.g:
x = 0: (x != 1 => true || x != 0 => false) => true
x = 1: (x != 1 => false || x != 0 => true) => true
x = 2: (x != 1 => true || x != 0 => true) => true
...

a while loop continues while the condition is true.
The condition you wrote is trivially always true for any value of x.
And number is always "different from 0" or "different from 1" (or both).
Hence, the infinite loop.
Maybe you thought `||, the logical 'or', meant "either the first one or the second is true, but not both" ?
If you want to have "x != 0 or x != 1, but not both", then you actually meant x == 0 || x == 1

I think I understand my erroneous thinking now.. with an || expression, if the first expression evaluates to false, the second is always also evaluated. I was under the impression that similar to &&, if one expression in an || is false, the entire is interpreted as also false, but turns out (false || true) = true while (false && true) = false as well as (true && false) = false, but unlike the ||, in an &&, the compiler doesn't even bother evaluating the second expression when the first yields false but an || evaluates both only if the first is false. I think I got it...

Related

what is the meaning of "!x" in "while(!x && i < n)"

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

What does the exclamation point in if (!strcmp() ... do?

Can someone explain what the exclamation point in the if statement does (i.e. !strmcp)?
string names[] = {"EMMA", "RODRIGO", "BRIAN", "DAVID"};
// Search for EMMA
for (int i = 0; i < 4; i++)
{
if (!strcmp(names[i], "EMMA"))
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;
For an if statement, if the expression evaluates to 0, then the block of code following the if statement is not executed. Any other value (positive or negative), will result in executing the code block. The function strcmp uses 0 to say that strings are equal because less than 0 is used to differ from greater than 0.
So in this code, we want printf("Found\n"); to be executed when the strings are equal. Since strcmp results in 0, we need to negate the value so that it becomes 1 which will result in executing that code block.
strcmp() returns 0 if the strings are identical, so you need to negate it, if you use it in an if clause to assert a true statement.
If your clause is if(0), the code inside the condition will not be executed.
For completion, it returns negative if the first different character found is lower in the first string, for instance:
first parameter string: "abca"
second parameter string :abcd"
This will return negative. If it's the other way arround it will return positive.
Also, string is not usually used in C (I refer you to Jonathan Leffler's commment), you can use char*:
char *names[] = {"EMMA", "RODRIGO", "BRIAN", "DAVID"};
Unary operator ! is called the logical NOT operator (cf., for example, this definition at cppreference.com). ! expression returns 1 if expression evaluates to 0, and it returns 0 if expression evaluates to anything else but 0.
So the condition in if (!0) gives 1; this means, the condition is met and the if-block is entered. It has the same meaning as if(0==0)
Consequently, the meaning of
if(!strcmp(names[i], "EMMA"))
in your code is exactly the same as
if(0==strcmp(names[i], "EMMA"))
And you already know when strcmp returns 0...
The exclamation point is the C's boolean negation character.
It means give me the boolean opposite of the value. A boolean is either true or false, which are 1 or 0 in the C Language.
In C, if statements execute their conditional statements if the argument is true.
if (a) means if a is true (i.e. non-zero)
if (!a) means if a is false (i.e. 0)
Therefore:
if (a) is the same as if (a != 0)
if (!a) is the same as if (a == 0)
Sometimes you'll see code that uses two exclamation points in a row "!!"
For example:
int a = !!b;
That ensures a will be ONLY 0 or 1, regardless of what the value of b is.
If b is ANY non-zero value, the ! operator will treat it as though it is true true, which it treats as being the same as 1
So:
!0 == 1
!1 == 0
!52 == 0
!25692 == 0
The second ! does the boolean inversion again, so:
!!0 == 0
!!1 == 1
!!52 == 1
!!25692 == 1
In C any non zero value is considered ad the logical truth, zero i considered as logical false. ! is a logical negation. So !0 (not false) will be the truth and if(!strcmp(str1,str2)) {statements} statements will be executed when str1 will be same as str2

Which condition is true in While?

Sorry if this is too simple. I want to know which of the conditionals is happening exactly. Is there a way more able to capture this without repeating them inside the block with if structures? I am using C language.
while ( l < 0 || l > 2 || c < 0 || c > 2 )
You could use comma expressions, i.e. something like (expr1,expr2), which are always evaluated left to right with a sequence point at each ,; So you may rely on that expr1 is evaluated before expr2, whereas the latter serves as the comma expression's result then.
With that, the following should work, and x will bee in the range of 0..3, depending on which condition got true:
int x;
while ( (x=0,l < 0) || (++x,l > 2) || (++x,c < 0) || (++x,c > 2) )
You can assign them "on the fly" to previously declared variables:
bool ll0, lg2, cl0, cg2;
while((ll0 = l<0) || (lg2 = l>2) || (cl0 = c<0) || (cg2 = c>2)) {
if(ll0) {
// l is less than 0
} else if(lg2) {
// l is greater than 2
} else if(cl0) {
// c is less than 0
} else if(cg2) {
// c is greater than 2
}
// ...
}
Notice the if-else chain, as, since the || operator short-circuits (i.e. the second operand isn't even evaluated if the first is already true), if e.g. ll0 is true the other values aren't going to be correctly assigned.
That being said, to be honest I wouldn't bother - just repeat the conditional, if these are just integer variables these comparisons aren't going to cost you anything (actually, the compiler may even keep around the comparison value in some cases and recycle it).
You could use a loop without conditions, compute conditions in loop, and break if any of the conditions is true.
while (1) // or for(;;)
{
bool one = l < 0;
bool two = l > 2;
bool three = c < 0;
bool four = c > 2;
if (one || two || three || four) break;
// bool variables are available there
}
If you want to get access to all conditions, you cannot use short-circuiting evaluation for them. So make sure you really want to store them beforehand.

I am facing difficulty to understand this program [duplicate]

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.

if-else condition in C

In C language, what is the result of x=0 if I put it in if-else condition? if it is represent false or if this assignment is finished, then represent true?
my colleague write code as:
if(condition = 0)
{
//do process A
}
else
{
// do process B
}
obviously, this code is wrong, I know it should be condition == 0 or ((condition=foo()) == 0) but my assumption is program should always do process A because i think if(condition = 0) should always return true since this is set value 0 to variable condition and this set process should be true. However, program always do process B, that means if use the variable condition value and my assumption is wrong.
Then I did a another test code:
if(condition = 2) //or other none-zero value
{
//do process A
}
else
{
// do process B
}
this time, program always do process A.
My question is why if-else condition does not use the operation value of condition but use the left variable after setting?
when you assign 0 to variable condition it becomes false as 0 represents false and any non-zero value represents true.so, when you assign 0 else condition is executed and when you assign 2 condition represents a true statement so, it executes...
if(condition = 0)
after assigning value 0 to condition it becomes
if(condition)
and as it is false, it doesn't execute.but, when condition = 2, it works in the same way and become true .so, the if condition is executed then.
You use wrong operator.
a = 10;
The "equals" operator means "assign value to".
Now to compare two operands, a and b, to see if a = b, you use another operand.
That operand is double equals (==).
if(variable == 0)
{
//do process A
}
else
{
// do process B
}
Now look.
If the variable with name "variable" has value = 8 that is not equal to 0,
thus the whole "variable == 0" expression if FALSE.
So proccess B will run.
If otherwise variable is equal to 0 indeed, proccess A will be executed because "variable == 0" is true.
It's like:
if(EXPRESSION)
{
// EXPRESSION IS TRUE
}
else
{
//EXPRESSION IS FALSE
}
Got it? :)
In C, assignment is an expression that returns the set value; i.e. x = 2 will result in 2.
This allows you to do something like this:
unsigned char ch;
while((ch = readFromFile(f)) != EOF) {
// do something with ch
}
It also allows you to shoot yourself in the foot if you accidentally mistype == as =, which is why this 'feature' doesn't appear in a lot of other languages.
In your first loop, the expression condition = 0 will always result in 0, causing the else branch to be taken. Similarly, condition = 2 results in 2, which causes the true branch to be taken.

Resources