I'm new in programming and my test is going to be soon, but I have no idea what happens in this for loop. Could someone explain it to my. I'd be very thankful :)
I'm new in programming and my test is going to be soon, but I have no idea what happens in this for loop. Could someone explain it to my. I'd be very thankful :)
It's nothing fancy. It's just a simple for loop with some compound statements. let me explain every bit of it.
The syntax ( writing sequence ) of for loop is below.
for(initial value for loop ; condition to check on every loop ; increment in initial value)
{
body of loop
}
First Line :
int[] a = new int[6];
This line is only declaring an INTEGER ARRAY of length 6
Second Line :
for(int i=0; i<=10 ; i=i+2) a[i/2] = i < 5 ? 5 - i : 0 ;
This is a compound statement, First simplify this.
The above CODE can be written as
for (int i=0 ; i<=10 ;i=i+2)
{
if(i < 5)
{
a[i/2] = 5 - i;
}
else
{
a[i/2] = 0;
}
}
Third Line :
for(int i=a.length ; i > 0 ; i--) a[i-1] = a[a[i-1]] + i ;
The above code can be written as followed
for(int i = a.length ; i > 0 ; i-- )
{
//decomposing a[a[i-1]]
//lets assume that **i = 2** and **a[1] = 99**;
a[ value of a[i-1] which is a[2-1] => a[1] which is 99 ];
// so after putting value of a[1] the above equ will be
a[99]
//this is also be equal to some value, let say a[99] == 40;
//then
a[i-1] = 40 + i;
}