How to get rid of initialization after first of two for-loops?

This is not the same as the code that you’ve linked to. The original has y indexed, i.e., it is an array:

for (i=0; i<N; i++) {
   y[i] = 0.;
   for (j=0; j<N; j++)
      y[i] += ...
}

This could be rewritten as:

for (i=0; i<N; i++)
  y[i] = 0.;

for (i=0; i<N; i++)
  for (j=0; j<N; j++)
    y[i] += ...
}

In your case, y is scalar. Each iteration of the outer loop resets its value to 0 before the inner loop. If there are no side effects in the inner loop, only the last iteration of the outer one counts and you can simply get rid of it:

i = N-1;
y = 0.;
for (j=0; j<N; j++)
  y += ...

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top