Please Explain the code given below... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Please Explain the code given below...

#include <iostream> using namespace std; int main() { int a=7,b=1; if(a=8||b==5) cout<<a*b; cout<<" "<<a; return 0; } // Output : 1 1

1st May 2019, 12:42 PM
Sp Maurya
Sp Maurya - avatar
4 Answers
+ 20
Initial values of a=7,b=1; Here you are checking a condition if(a=8||b==5) I.e. here you are checking if a is equal to 8 OR b==5 then as you wrote 8, the expression is evaluated to be TRUE so 1 goes into a. So the value of a becomes 1 and b is already 1so 1*1 is also 1. If you want the correct output then add parenthesis across each condition like this if((a=8)||(b==5)) and then check the output. It will be 8 (for a) and 8 (for 8*1). Edit : You wrote a=8 in the condition which means 8 can be assigned as the new value of a, so don't know if it was by mistake or you knew while writing. But just was warning you as it can change the output 😅. Hope this helps !!!
1st May 2019, 1:03 PM
Nova
Nova - avatar
+ 7
If you wrote the `if` statement correctly (the `a = 8` wasn't mistaken for `a == 8`) then I guess the evaluation in `if` statement goes like this: if(a = (8 || b == 5)) if(a = (true || false)) You see, the expression following the `a = ` is evaluated as boolean expression, this happens because we are comparing 8 (int, assumed true) with a boolean expression `b == 5` using || operator (logical OR). The expression evaluates to true, because logical OR operator yields true when either operands were true (in this case 8 represents true, while `b == 5` represents false). So what we see here, variable <a> is assigned a new value which was a boolean true (1 in numeric form). In the end, we print <a>, who's value is now 1, multiplied by <b>, which gives us 1 * 1. Next, print a space followed by value of <b> which was not altered (still 1). That's the output `1 1` Hth, cmiiw
1st May 2019, 1:53 PM
Ipang
+ 3
Oh i got it and it wasn't a mistake actually it is a quiz that i had found in a challenge, so a=8 is correct... Thanks for your help... Keval and Ipang
2nd May 2019, 3:59 AM
Sp Maurya
Sp Maurya - avatar
+ 3
You're welcome Sp Maurya, glad if it helps 👍
2nd May 2019, 5:16 AM
Ipang