[Solved] for loop: make increment and accessing in one loop


doing

for(
    int i =0;
    i++<10;
    a[i-1]=i
   )
 {
  printf("%i:%i\n", i-1, a[i-1]);
 }

you set the entries after you print them because a[i-1]=i is executed after the body of the for, so you print non initialized array entries

your code is also ‘complicated’ because you increase i too earlier in the test part of for, a ‘standard’ way to do what you (probably) want is :

for(int i = 0; i < sizeof(a)/sizeof(*a); ++i) {
  a[i]=i+1;
  printf("%i:%i\n", i, a[i]);
}

if you really want to not have a[i]=i+1; in the body you can do that :

for(int i = 0; (i < sizeof(a)/sizeof(*a)) && (a[i]=i+1); ++i) {
  printf("%i:%i\n", i, a[i]);
}

to avoid a warning when compiling do ... && ((a[i]=i+1) != 0);

note (a[i]=i+1) is not false because values at least 1, in case you wanted to do a[i]=i the test to use can be (i < sizeof(a)/sizeof(*a)) && (a[i]=i, 1) to not be false when i is 0

but that does not help to read the code ^^

2

solved for loop: make increment and accessing in one loop