gfdsal
gfdsal

Reputation: 721

For-Loop with Unrelated Conditions

I am having difficulty understanding the following for-loop with multiple unrelated conditions:

double init, P[500],ta[500][500];
int a, i, N;
N=100;
P[0]=1;
for(init = 1., i = 0; i < N+1; P[i+1] = P[i] * 100, i++)
    for(a=0;a<N+1;a++)
       ta[i][a]=1.;

I understand in a normal situation it shall be the counter i that is initialized to 0 and will be incremented till the condition i<N+1 but what about init=1, P[i+1]=P[i]*100 and how do they fit in?

Upvotes: 0

Views: 138

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35164

Expressions like init = 1., i = 0 are called comma expressions. Each subexpression is evaluated separately, one after the other. So before entering the for-loop the first time, both init=1 and i=0 get executed. The for loop's condition is simply i<N+1, and - after each iteration - the comma expression P[i+1] = P[i] * 100, i++ will be evaluated (i.e. P[i+1] = P[i] * 100 and then i++. That's all.

Upvotes: 1

Raj Kumar
Raj Kumar

Reputation: 1587

Every for loop has an initialization section, a condition section and a change of value section. They need not reuse the same variables. They can all be unrelated. So init = 1., i = 0; is the initialization section. In the condition section here i < N+1; all the loop cares for is a boolean value, which it gets. It does not matter where that value comes from. For the change of value mostly used for incrementing / decrementing values P[i+1] = P[i] * 100, i++. This is what is done. For all it matters you can leave that section blank and the program will still work. You can do the change inside the loop. All a for loop gives you is an elegant way to write an iteration. Doesn't mean that it is the only way to use it.

Upvotes: 2

Related Questions