0

Can I have 2 initializers, 2 conditions, 2 iterators?

for (initializer; condition; iterator){
    body
}

I am asking this because I want to compare 2 arrays

int[] v1 = new int[10];
int[] v2 = new int[10];

for(int i=0; int j=v2.Length; i<v1.Length; j>0; i++; j--)
{
     if(v1[i]==v2[j])
     {
        //do something
     }
} 

3
  • 1
    yes - separate with a comma instead of semi-colon: for(int i=0, int j=v2.Length; i<v1.Length, j>0; i++, j--) Commented Oct 31, 2020 at 17:33
  • You could just use 1 variable though. if(v1[i]==v2[v2.Length - i]) or similar Commented Oct 31, 2020 at 17:35
  • 1
    @AndrewS that doesnt compile. Commented Oct 31, 2020 at 17:35

1 Answer 1

2

Not exactly, you can declare and initialize multiple loop variables, but they need to have the same type. Further, you cant have multiple conditions, but you can combine them via logical operators:

for (int i = 0, j = 1; i < v1.Length && j > 0; i++, j++  )
{
    if (v1[i] == v2[j])
    {
        //do something
    }
}

what also works is to initialize earlier declared variables of different types:

int i; double j;
for ( i = 0, j = 1.5; ... )
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.