+6

# Boolean logic and loops

When does Boolean logic apply to an if loop? I'm certain I've seen it applied before, but in the following code it's not applicable: #include <iostream> using namespace std; int x = 1; int y = 1; int main() { if (x + y == 1) {cout << "It worked"<<endl;} else cout << "It didn't work" << endl; return 0; }

9/24/2017 7:56:55 AM

21kHzBANK21kHZ

+23

The code works perfectly. 1 + 1 is 2 and 2 is clearly not 1. The code outputs "It didn't work".

+26

First of all, if statement isn't a loop - it's a conditional statement like the switch. Whatever you put in an if statement, boils down to a boolean "true/1" or "false/0" value. For example: // Example program #include <iostream> #include <cmath> using namespace std; int main() { int a = -1; int b = 128; int c = 0; float d = 1.45f / 98.0f; double e = (2.71 + 3.14) * 30.0; double f = sin(e); char g = 'H'; long long h = 12345678912345; if (a) cout << "a Done.\n"; if (b) cout << "b Done.\n"; if (c) cout << "c Done.\n"; if (d) cout << "d Done.\n"; if (e) cout << "e Done.\n"; if (f) cout << "f Done.\n"; if (g) cout << "g Done.\n"; if (h) cout << "h Done.\n"; } https://code.sololearn.com/chAYAQ13fHDD

+20

So give up vote to all friend who clarified the point for you, my friend.

+20

Thanks dear Hatsy for useful tip. really worth to put it in my tutorial series. @~)~~~~

+14

Indeed, anything which is not 0 and not false is evaluated to true in C++, but in if (1 + 1 == 1) All the values are taken as integer values. Hence LHS and RHS value does not tally, and the statement is evaluated as false. Try doing if (bool(1 + 1) == true) // or if (bool(1 + 1) == 1) These will yield different results.

+12

Also, the 'if' keyword is associated with conditional statements. There is no such thing as 'if loops'.

+6

if (x+y==1) comes the boolean

+5

I think boolean logic will not work here so here, 1+1==2 and not 1 as both the 1's are taken as decimal numbers, not binary numbers. So if statement doesn't executed and it shows "It didn't work".

+5

Okay, I got confused because if I write something like "int i =5; if (i == 5)" this evaluates to if (true)." I thought that in this case as long as the number was anything other than 0 the code would consider the statement true, as in boolean logic, but this is not the case. It checks the condition truthfully, then the answer becomes 1 (true) or 0 (false). Thanks.

+4

First up, if statement is not a loop... It will execute when the condition is true, and not when it is false. if is a conditional statement.

+2

True. If-statements

+1

true if statement..

0

Boolean logic