Home > Enterprise >  C: for loop with two variables and circular shift
C: for loop with two variables and circular shift

Time:02-25

I could not figure out how the following for loop works.

#include <stdio.h>

int main()
{
  int i, j, n=4;
  for (i = 0, j = n-1; i < n; j = i  )
      printf("\ni: %d, j:%d", i, j);
    
 return 0;
}

Which produces:

i: 0, j:3
i: 1, j:0
i: 2, j:1
i: 3, j:2

The increment rule j = i confuses me. I do not get the circular shift behavior of j. Also, there is no increment rule for i and it increases by 1. Can someone explain?

CodePudding user response:

The for loop written in that form

for(init; cond; incr) { instruction bloc }

can be rewritten in that form :

init;
while(cond) 
{ 
    instruction bloc;

    incr;
} 

So you can write your loop another way:

int i, j, n=4;

// first parameter of for loop
i = 0;
j = n-1; 

// second parameter of for loop : while the condition is true, stay in instruction bloc
while( i < n) {

    // instruction bloc
    printf("\ni: %d, j:%d", i, j);

    // third parameter: executed after instruction bloc
    j = i  
}

Hence you can understand how i and j are increased:

j = i  ;

Could be rewritten:

j = i;
i = i   1;
  • Related