Related
I am attempting to solve a hw problem in which I need to write down what the program will output. I am stuck however, on the syntax "if ( !(i%3)). What does that really mean? Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
int main () {
for (int i=0; i<10; (i<3?i++;i+=2)) {
if (!(i%3)) {
continue;
}
else if (i%7 ==0) {
break;
}
cout << i<< endl;
}
Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
Correct. The longer version of that check would be
if (i % 3 == 0)
continue;
The most common use case for such branching is probably FizzBuzz.
İt means if i is not(!) divisible by 3 continue.
For example if i is 3,6,9 it won't continue otherwise it will continue.
if (x) where x is int implicitly compared with zero. I.e. if (x) equals to if (x != 0). ! is negation. So if (!x) equals to if (x == 0). And the last step is if (!(i%3)) equals to if ((i%3) == 0) what is the same with check, that i deivisible by 3
The if() statement is false only if the result inside the parentheses is 0 (false). Take a look at your program:
i%3 may return 0 (false), 1 (true), or 2 (true)
The negation operator ! changes the result of the operation (i%3). So, if the i is divisible with 3 the statement will return 0 (false). Being negate, ! it will result in True. Otherwise the result of (i%3) will be true and with the operator ! the result of the hole statement will be false. Basically this code is checking if the value of i is divisible with 3.
Other options will be:
if (0==i%3)
{
/*code*/
}
Your code can be simplified as below
int main() {
for (int i=0; i<10;)
{
if (i % 3 == 0) {
continue;
}
else if (i % 7 == 0) {
break;
}
cout << i << endl;
i = i<3 ? i+1 : i+2;
}
}
When you write a integer variable like i as a condition, what happens is that if i==0 then the result of the condition is false, otherwise it would be true.
Let's check it out in your program, if(!(x%3)), let's name condition= !(x%3), when this condition is true? when x%3 == 0, note that the negation operator ! is behind x%3, so in this case the condition would be equal to true, more formally the condition is equal to :
if(x%3==0)
these kinds of conditions are common, check this example out :
int t = 10;
while(t--){
cout<<t<<endl;
}
The above condition i.e if(!(i%3)) will true when " i is not disvisable by 3"
Hope this helps.
In java and other languages there is a special type to represent booleans and evaluate expressions; in c and its variants there is no such thing, instead an expression is considered "true" if -taken as a integer number- is equal to 0; false for every other value. (Fun fact: this is why you usually end the code by return 0)
So if(x%3) in c is equivalent to if(x%3==0) in other languages. That said, if(x%3) execute the if body when the remainder of x/3 is 0, that is when x is a multiple of 3.
In your code you have the ! before, that -as you may know- "inverts" the expression. That means that if(!(x%3)) can be read as "If the remainder of the integer division of x by 3 is not 0", or alternatively: "If x is not a multiple of 3".
So, basically, you saw it right.
Hope I helped!
I am just starting out programming and reading thru C++ Programming Principles and Practice. I am currently doing the Chapter 3 exercises and do not understand why this code I wrote works. Please help explain.
#include "std_lib_facilities.h"
int main() {
cout<<"Hello, User\n""Please enter a number (Followed by the 'Enter' key):";
int number=0;
cin>> number;
if (number%2) {
cout<<"Your number is an odd number!";
} else {
cout<<"Your number is an even number\n";
}
return 0;
}
When number is odd, number%2 is 1.
if (number%2) {
is equivalent to
if (1) {
Hence, you get the output from the line
cout<<"Your number is an odd number!";
When number is even, number%2 is 0.
if (number%2) {
is equivalent to
if (0) {
Hence, you get the output from the line
cout<<"Your number is an even number\n";
The modulus operator simply determines the remainder of the corresponding division problem. For instance, 2 % 2 returns 0 as 2 / 2 is 1 with a remainder of 0.
In your code, any even number entered will return a 0 as all even numbers are, by definition, divisible by 2 (meaning <any even number> % 2 == 0)
Likewise, any odd number entered will return 1 (for instance, 7 % 2 == 1 as 7 / 2 has a remainder of 1).
In c++, like in many programming languages, numeral values can be treated as booleans such that 0 relates to false while other numbers (depending on the language) relate to true (1 is, as far as I know, universally true no matter the programming language).
In other words, an odd number input would evaluate number % 2 to 1, meaning true. So if (number % 2), we know that the input number is odd. Otherwise, number % 2 must be false, meaning 0, which means that the input number is even.
"if" statements works on boolean values. Let's remember that boolean values are represented by "false" and "true", but in reality, it's all about the binary set of Z2 containing {0, 1}. "false" represents "0" and "true" represents "1" (or some people in electronics interpret them as "off/on")
So, yeah, behind the curtains, "if" statements are looking for 0 or 1. The modulus operator returns the rest of a / b. When you input any number and divide it by 2, you are gonna get a rest of 0 or 1 being it pair or an odd number.
So that's why it works, you will always get a result of 0 or 1 which are false and true by doing that operation that way.
think of modulus in terms of this:
while (integer A is bigger than integer B,)
A = A - B;
return A
for example, 9%2 -> 9-2=7-2=5-2=3-2=1
9%2=1;
the statement if (number%2) is what is called a boolean comparison (true false). Another way to write this statement identically is if(number%2 != 0) or if(number%2 != false) since false and zero are equivocal. You're taking the return value of the modulus operator function (a template object we will assume is an integer) and inserting it into an if statement that executes if the input does not equal zero. If statements execute if the input is -5,9999999,1-- anything but zero. So, if (2) would be true. if(-5) would also be true. if(0) would be false. if(5%2) would be 1 = true. if(4%2) would be if(0) = false. If it is true, the code in the body of the if statement is executed.
So I have this function that takes in an integer. But It doesn't work and I suspect that the if statement is not valid, I could not find anything on google regarding the issue, maybe my googling skills just suck.
if mynumber != (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8) then
print("Please choose an integer number between 1-8")
end
Thanks for any help!!
Correct. That is not how you test things like that. You cannot test multiple values that way.
or requires expressions on either side and evaluates to a single expression. So (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8) evaluates to 0 and your final expression is just if mynumber != 0 then.
To test multiple values like that you need to use or around multiple comparison expressions.
if (mynumber ~= 0) or (mynumber ~= 1) or (mynumber ~= 2) ... then (also notice ~= is the not-equal operator not !=).
Also be sure to note YuHao's answer about the logic in this line and how to test for this correctly.
Others have pointed the major problems you have, i.e, 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 evaluates as 0, the rest is ignored because of short-circuit. You need to test the number with these numbers one by one.
However, there's one last trap. The condition
if mynumber ~= 0 or mynumber ~= 1 then
is always true, because a number is either not equal to 0, in which case mynumber ~= 0 is true; or it is equal to 0, in which case mynumber ~= 1 is true.
The correct logic should be:
if mynumber ~= 0 and mynumber ~= 1 then
Etan's answer explains the behaviour as observed in lua. I'd suggest writing a custom FindIn function for searching:
function FindIn( tInput, Value )
for _ in pairs( tInput ) do
if Value == tInput[_] then return true end
end
return false
end
if FindIn( {1,2,3,4,5,6,7,8}, mynumber ) then
-- ...
end
try this:
In Lua You check if two items are NOT EQUAL by "~=" instead of "!=",
If You compare two items in if statement, then always remember that items should return booleans, so: instead of mynumber != (0 or 1 or...) try something like (mynumber ~= 0) or (mynumber ~= 1) ...
You can do it simple with .... (mynumber have to be integer variable)
if mynumber<0 or mynumber>8 then
print("Please choose an integer number between 1-8")
end
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
I came across this on codegolf
Please explain the usage of ? and : and why is there no statement following the while loop? As in why is there a ; after the parenthesis.
There is a boolean operation going on inside the parentheses of the while loop:
while (boolean);
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. It looks more like a code obfuscation runner up. But it appears to be compilable and runnable. Did you try it? What did it do?
The ?: is a ternary operator.
An expression of form <A> ? <B> : <C> evaluates to:
If <A> is true, then it evaluates to <B>
If <A> is false, then it evaluates to <C>
The ; after the while loop indicates an empty instruction. It is equivalent to writing
while (<condition>) {}
The code you posted seems like being obfuscated.
Please explain the usage of ? and :
That's the conditional operator. a ? b : c evaluates a and converts it to a boolean value. Then it evaluates b if its true, or c if its false, and the overall value of the expression is the result of evaluating b or c.
So the first sub-expression:
assigns t-i%10 to i. The result of that expression is the new value of i.
if i is not zero, the result of the expression is i/10
otherwise, print j, and the result of the expression is zero (since printf returns a non-zero count of characters printed, which ! converts to zero).
Then the second sub-expression, after ||, is only evaluated if the result of the first expression was zero. I'll leave you to figure out what that does.
why is there no statement following the while loop?
There's an empty statement, ;, so the loop body does nothing. All the action happens in the side effects of the conditional expression. This is a common technique when the purpose of the code is to baffle the reader; but please don't do this sort of thing when writing code that anyone you care about might need to maintain.
This is the Conditional Operator (also called ternary operator).
It is a one-line syntax to do the same as if (?) condition doA else (:) doB;
In your example:
(i=t-i%10 ? i/10 : !printf("%d\n",j)
Is equivalent to
if (i=t-i%10)
i/10;
else
!printf("%d\n",j);
?: is the short hand notation for if then else
(i=t-i%10 ? i/10 : !printf("%d\n",j)<br>
equals to
if( i= t-i%10 )
then { i/10 }
else { !printf("%d\n",j) }
Your while loop will run when the statement before the || is true OR the statement after the || is true.
notice that your code does not make any sense.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
in the most human-readable i can do it for u, it's equivalent to:
while (i < 101)
{
i = (t - i) % 10;
if (i > 0)
{
i = i / 10;
}
else
{
printf("%d\n",j);
}
i = ++j;
if (i < 0)
{
i = i - j;
}
else
{
i = j;
}
}
Greetings.
I am the proud perpetrator of that code. Here goes the full version:
main()
{
int t=getchar()-48,i=100,j=-i;
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
}
It is my submission to a programming challenge or "code golf" where you are asked to create the tinniest program that would accept a digit as a parameter and print all the numbers in the range -100 to 100 that include the given digit. Using strings or regular expressions is forbidden.
Here's the link to the challenge.
The point is that it is doing all the work into a single statement that evaluates to a boolean. In fact, this is the result of merging two different while loops into a single one. It is equivalent to the following code:
main()
{
int i,t=getchar()-'0',j=-100;
do
{
i = j<0? -j : j;
do
{
if (t == i%10)
{
printf("%d\n",j);
break;
}
}
while(i/=10);
}
while (j++<100);
}
Now lets dissect that loop a little.
First, the initialisation.
int t=getchar()-48,i=100,j=-i;
A character will be read from the standard input. You are supposed to type a number between 0 and 9. 48 is the value for the zero character ('0'), so t will end up holding an integer between 0 and 9.
i and j will be 100 and -100. j will be run from -100 to 100 (inclusive) and i will always hold the absolute value of j.
Now the loop:
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
Let's read it as
while ( A || B ) /* do nothing */ ;
with A equals to (i=t-i%10?i/10:!printf("%d\n",j)) and B equals to (i=++j<0?-j:j)<101
The point is that A is evaluated as a boolean. If true, B won't be evaluated at all and the loop will execute again. If false, B will be evaluated and in turn, if B is true we'll repeat again and once B is false, the loop will be exited.
So A is the inner loop and B the outer loop. Let's dissect them
(i=t-i%10?i/10:!printf("%d\n",j))
It's a ternary operator in the form i = CONDITION? X : Y; It means that first CONDITION will be evaluated. If true, i will be set to the value of X; otherwise i will be set to Y.
Here CONDITION (t-i%10) can be read as t - (i%10). This will evaluate to true if i modulo 10 is different than t, and false if i%10 and t are the same value.
If different, it's equivalent to i = i / 10;
If same, the operation will be i = !printf("%d\n",j)
If you think about it hard enough, you'll see that it's just a loop that checks if any of the decimal digits in the integer in i is equal to t.
The loop will keep going until exhausting all digits of i (i/10 will be zero) or the printf statement is run. Printf returns the number of digits printed, which should always be more than zero, so !printf(...) shall always evaluate to false, also terminating the loop.
Now for the B part (outer loop), it will just increment j until it reaches 101, and set i to the absolute value of j in the way.
Hope I made any sense.
Yes, I found this thread by searching for my code in google because I couldn't find the challenge post.
Sorry for this newbie question, but I can't find on google what I need to know.
I understand return, but don't understand this... What does it mean this?
return (tail+1)%N == head%N;
Thanks a lot for patience.
It returns true or false, depending on whether the expression is true or not.
It's the same as:
if ( (tail+1)%N == head%N )
return true;
else
return false;
this
(tail+1)%N == head%N
returns a boolean value, either true or false. This statement means that after adding 1 to trail (trail + 1) and the remainder obtained after division with N is equal to remainder of head divided with N. % is used for division with remainder
(%). Modulo is the operation that gives the remainder of a division of two values.
Check this link for c++ operators : http://www.cplusplus.com/doc/tutorial/operators/
you're returning a boolean value. The value represents whether or not the remainder of (tail+1) divided by N is the same as that of head.
It evaluates the expression, and return the result. In this case it's two modulo operations that are compared, and the result is either true or false which will be returned.
Short Answer:
Because of the == operator your function will return a bool, meaning it can only be trueor false. An equivalent would be something like:
return 5 == 4;
which would return false since 5 is not equal to 4.
Long Answer:
Instead of writing this in a single line you could split it up into more lines of code. Let's just assume that tail, head and N are integer values, then you could write it like this:
int x, y;
x = (tail+1)%N;
y = head%N;
if ( x == y )
{
return true;
}
else
{
return false;
}
Now in this code there may be also that %confuses you a bit. The %is called the Modulus Operator and can give you the remainder of arithmetic operations. In a simple example this would mean:
10 % 3 = 1 because 10/3 is 3 with a remainder of 1. So to make it more clear let's just make another example with your specific problem:
Lets just assume that tail=10,head=6 and N=2. Then you would get something like this:
x = (10+1)%2
x = 11 % 2
x = 1
y = 6 % 2
y = 0
y != x
This would return false cause x and y are not equal. ( If you would run your code with the given example values )
To learn more about Modulus you can look here, or just on any other basic C++ Tutorial.
it returns true if remainder of the division for tail + 1 and head is the same
for example if tail is 2, head is 1 and N is 2
(tail + 1) % N is 1
head % N is 1 too
so whole expression returns true