Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C: for loop with two variables and circular shift

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading