Reputation: 11
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
}
}
Upvotes: 0
Views: 55
Reputation: 13684
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; ... )
Upvotes: 2