0

In the given code, why the result of the addition is not captured in iteration? Why x's value never changes?

public class Fortran {
    static int bump(int i) { return i + 2; }
    public static void main(String[] args) {
        for(int x = 0; x < 5; bump(x))
        System.out.print(x + " ");
    } 
}
1
  • Change the last line in your for statement to read x =bump(x). You're not capturing the result. Commented Dec 22, 2013 at 14:19

2 Answers 2

3
  1. Java passes values by copying, so bump only gets a copy of x

  2. The value returned by bump is never assigned to x (perhaps you forgot x =).

Perhaps try

for(int x = 0; x < 5; x = bump(x))
Sign up to request clarification or add additional context in comments.

Comments

0

It's just cause your new value is never assigned. The correct way of doing that is more.

for(int x=0;x<5;x+=2)
{
    //do whatever you want
}

NB : x+=2 is a short writing for x=x+2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.