+ 1

Find the value of z (Try solving this amazing post/pre operators question! It will make your concept clear forever :D)

Code: <script> var a =3; var b = 2; var z =(++b+a--)%5; document.write("The result is " + z + "!<br>"); document.write("Also, value of a is " + a + " and value of b is " + b); </script> Can anyone solve this? (Check the reply section for this comment and see the answer with explaination!) Try running it too! :P

12th Feb 2017, 3:11 PM
Divyanshu Kushwaha
Divyanshu Kushwaha - avatar
3 Respostas
+ 3
Post increment or decrement operators, i.e. a++ or a-- , name clarifies everything. In English how I leared is, "Perform whatever operation you have to do with 'a' and then increment or decrement it's value by 1", 'POST' just feel this word, as 'LATER INCREMENT' or 'LATER DECREMENT', depending on what you use! Now same with 'PRE INCREMENT' or 'PRE DECREMENT', i.e. ++a or --a , "First increment or decrement the value of a, and then dare to perform any operation with it" :D Thus, in this case i.e., a = 3, b = 2, z = (++b+a--)%5, lets simplify this equation first and then try to solve it, => z = ( ++b + a-- ) % 5; i.e, pre increment 'b' by 1 , add the result to 'a' and then post decrement 'a' => z = ( (b = b+1) + a--) % 5, where b= 3, since 'b' has 'PRE INCREMENT' and 'a' will remain 3, since 'a' has a 'POST DECREMENT' so it means decrement the value of 'a' only after you have performed operations on it, 'LATER DECREMENT' remember? So, the value of 'a' will be first added with 'b' and then stored within a temporary variable used by the program internally (which we are unaware of! ) Thus, it maybe 'temp' i.e, temp = b + a, where b is already 3 and 'a' is 3 too, so 'temp' will be 6 and then value of 'a' will be decremented by 1, i.e. a =2 now, which will be stored in program's memory counters but it wont affect our equation. => z = ( temp ) % 5 i.e. " where 'temp = 6', assign, value of, '6 % 5' to z. ( Remember, '%' is modulus operator, it means remainder, don't get confused with division '/' operator and '=' is the assignment operator!) => z = 1, thus 6 modulo 5 is 1, i.e if we divide 6 by 5 the remainder will be 1, Thus, the result is 1! Now if you wish to verify the value of a, you can perform : document.write(a), which will be 2 now. This is how variables are managed within the memory ! :)
12th Feb 2017, 6:07 PM
Divyanshu Kushwaha
Divyanshu Kushwaha - avatar
+ 1
thanks mate,i always find these pre and post increments kind of intriguing.would be glad if you post other such kind of equations :)
12th Feb 2017, 3:50 PM
nithin
nithin - avatar
+ 1
1
12th Feb 2017, 4:12 PM
Andre van Rensburg
Andre van Rensburg - avatar