1

Say we had the following python nested loop:

for i in range(0, len(A)):
  for k in range(i, len(A)):
     # Do something

What would be the java equivalent? This is what I got:

for (int i = 0; i < A.length ; i ++) {
  int j = i;
  for (j ; j < A.length ; j++) {
     // Do something
  }
}

1 Answer 1

3

Looks right to me, although you can declare j in the for loop.

for (int i = 0; i < number; i++) {
    for (int j = i; j < number; j++) {
        // Do something
    }
}

For the sake of completeness, python loops of this form:

for item in sequence:
    #do something

can be done in java as follows:

for (type item : sequence) {  //type being the type of the items in the sequence
    //do something
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this but I got the following error: Syntax error on token "j", ++ expected after this token
Sorry, I forgot to put 'int' before j.

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.