What does ! mean in C++?
Also, can you use %26amp;%26amp; and || in the following context
If (x == 0 %26amp;%26amp; y == 0)
{
cout %26lt;%26lt; "blah blah";
}
or the same thing but replacing %26amp;%26amp; with ||?
%26amp;%26amp;, ||, ! in C++?
! means logical not.
%26amp;%26amp; means logical and.
|| means logical or.
If you need further explanation of these, look at truth tables.
The following code is correct.
It will evaluate x. If x equals 0, then it will evaluate y. If y also equals 0 then it will output blah blah, otherwise it will not.
If (x == 0 %26amp;%26amp; y == 0)
{
cout %26lt;%26lt; "blah blah";
}
If you were to replace the %26amp;%26amp; with ||, then it would evaluate x. If x equals 0, then it will output blah blah. Then it will evaluate y. If y equals 0, then it will output blah blah, otherwise it will not.
If (x == 0 || y == 0)
{
cout %26lt;%26lt; "blah blah";
}
To use the ! symbol, this will only output blah blah if the expression evaluates to false, that is both x and y equal 0.
If (!(x == 0 || y == 0))
{
cout %26lt;%26lt; "blah blah";
}
Reply:Ya lerry is right ! is logical not.
see suppose if u have 2 values for x and y say
1. x=0;y=0;
2. x=0;y=1;
3. x=1;y=0;
4. x=1;y=1;
for statement
If (x == 0 %26amp;%26amp; y == 0)
{
cout %26lt;%26lt; "blah blah";
}
if input is 1 i.e. x=0, y=0
output blah blah
else for all other inputs i.e. 2,3,4, ands if statement will not execute.
similarly
for statement
If (x == 0 || y == 0)
{
cout %26lt;%26lt; "blah blah";
}
for input 1,2 and 3 it will print blah blah
and for input 4 it will not execute if loop.
Reply:That's the primary use for %26amp;%26amp; -- to join two logical expressions into a single one.
! is the negation operator: ! (False) == True
But %26amp;%26amp; and || are NOT interchangeable. %26amp;%26amp; means AND, while || mean OR. In fact, there's a theorem in logic named after the mathematician DeMorgan that relates %26amp;%26amp; and || this way:
!(A %26amp;%26amp; B) == ( !A || !B )
and
!(A || B) == ( !A %26amp;%26amp; !B )
So while the %26amp;%26amp; can be used in either context you mention,
(x == 0 %26amp;%26amp; y == 0) does not equal ( x == 0 || y == 0 )
Hope that helps.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment