Begginer here, trying to reduce code with a for loop iteration

please format code with </> button * homework policy * asking questions

I used for loop for simple things before… but now I have to do some addition in every increment.
My brain froze… I am drowning in code… Is there an easier way to write this?

Thanks

  TimeUp (Bl_1[0], 0, FPM_1[0], State_1[0]); // duration, start point
  TimeUp (Bl_1[1], Bl_1[0]+0, FPM_1[1], State_1[1]);
  TimeUp (Bl_1[2], Bl_1[0]+Bl_1[1], FPM_1[2], State_1[2]);
  TimeUp (Bl_1[3], Bl_1[0]+Bl_1[1]+Bl_1[2], FPM_1[3], State_1[3]);
  TimeUp (Bl_1[4], Bl_1[0]+Bl_1[1]+Bl_1[2]+Bl_1[3], FPM_1[4], State_1[4]);
  TimeUp (Bl_1[5], Bl_1[0]+Bl_1[1]+Bl_1[2]+Bl_1[3]+Bl_1[4], FPM_1[5], State_1[5]);
  TimeUp (Bl_1[6], Bl_1[0]+Bl_1[1]+Bl_1[2]+Bl_1[3]+Bl_1[4]+Bl_1[5], FPM_1[6], State_1[6]);
  TimeUp (Bl_1[7], Bl_1[0]+Bl_1[1]+Bl_1[2]+Bl_1[3]+Bl_1[4]+Bl_1[5]+Bl_1[6], FPM_1[7], State_1[7]);
  TimeUp (Bl_1[8], Bl_1[0]+Bl_1[1]+Bl_1[2]+Bl_1[3]+Bl_1[4]+Bl_1[5]+Bl_1[6]+Bl_1[7], FPM_1[8], State_1[8]);
  TimeUp (Bl_1[9], Bl_1[0]+Bl_1[1]+Bl_1[2]+Bl_1[3]+Bl_1[4]+Bl_1[5]+Bl_1[6]+Bl_1[7]+Bl_1[8], FPM_1[9], State_1[9]);
  TimeUp (Bl_1[10], Bl_1[0]+Bl_1[1]+Bl_1[2]+Bl_1[3]+Bl_1[4]+Bl_1[5]+Bl_1[6]+Bl_1[7]+Bl_1[8]+Bl_1[9], FPM_1[10], State_1[10]);
2 Likes

Yes, there is.

Chrisir

For loop around the thing, one line

Replace 2nd parameter with a function that receives a number and returns the sum of the array elements up to that number using a for loop

Thanks a lot buddy, you helped before. I didnt think of the function.
Mitch

1 Like

Hi @laptophead,

If you don’t want to use a special function you can use such a logical approach

Cheers
— mnse

// assuming numerical values
float v = 0;
for (int i=0;i<iterations;i++) {
  TimeUp (Bl_1[i], v, FPM_1[i], State_1[i]);
  v += Bl_1[i];
}
1 Like

MNSE
That actually worked. Thanks a lot, I love the simplicity.

so v += Bl_1[i]; means to add all the Bls from zero to i?
Mitch

1 Like

Hi @laptophead,

it does exactly what your code do …

1st iteration v=0
2nd iteration v=0+Bl_1[0]
3rd iteration v=0+Bl_1[0]+Bl_1[1]
...
Nth iteration v=0+Bl_1[0]+Bl_1[1]+ ... + Bl_1[N-1]

So on each iteration v is changed to the above to save it for the next iteration.

Cheers
— mnse