Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock Exam doubt increment expresion

 
Jagdev Singh
Ranch Hand
Posts: 71
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I have the following code.


The output is 1,0.

According to mine the output should be 1,1.

Can somebody please explain tricky logic at line 1.
Thanks in advance.
 
Will Myers
Ranch Hand
Posts: 381
Java jQuery Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
at line 1 i is is assigned the value of 0 (before the increment) + 0 (which is what is returned from method f1)

so the call breaks down to
i = 0 + fi(1)

try changing the increment operator to the front ++i and it will return 1,1

have a look at what the increment operator does and when it does it....
 
Jagdev Singh
Ranch Hand
Posts: 71
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Will,
One most doubt.
if I am using

Then the output is 1 which is expected.But when following code is used

The output is 0 .
According to me
In i = i++ first i is assigned to zero then the increment takes place but why this increment is not shown in print statement.Even though it is modifying same variable i.
 
Will Myers
Ranch Hand
Posts: 381
Java jQuery Scala
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you don't need to do assignment so it should read:


prints 1

The reason the code prints 0 in your example is explained nicely here


 
Jagdev Singh
Ranch Hand
Posts: 71
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Will,
I got it.It is really tricky.The given article is explaining this in best way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic