r/cprogramming • u/thedraegonlord • Sep 22 '26
For command working weirdly
Edit: Declaring n as 1 and changing the for loop to (i = n-1; i > 0; --i) as was suggested seems to have worked. Still don't really get the logic behind it, neither why the order inside the for expression was affecting the result nor why changing the n to 1 from 0 and i to n - 1 made a difference. Aren't they the same value at the end? Anyway, thanks.
For some reason, my "for" command only works when I put the increment in the middle and the condition at the end. I have no clue what's going on but the code is working fine when I do this.
I'm using devc++, the rest of the code is me declaring global variables and asking the user for inputs to fill the arrays. Everything is working exactly as intended but breaks if I write the "for" the regular way.
for(i = n; i--; i>0){
printf("Codigo: %d", codigo\[i\]);
printf("\\nProduto: %s", nome\[i\]);
printf("\\nPeso: %.2f", peso\[i\]);
printf("\\nPreco: %.2f", preco\[i\]);
if(regiao\[i\]==1){printf("\nRegiao: Sudeste");
}
else if(regiao\[i\]==2){printf("\nRegiao: Sul");
}
else if(regiao\[i\]==3){printf("\nRegiao: Nordeste");
}
else if(regiao\[i\]==4){printf("\nRegiao: Norte");
}
printf("\\n\\n");
View all comments
Show parent comment
1
u/thedraegonlord Sep 23 '26 edited Sep 23 '26
Could you clarify? With (i = n; i >0; i--) it sometimes prints a "product" where all variables are 0. I assume that's what you mean by access outside array limits, probably getting those 0s from an array position with no inputs. They're all size 100 btw.
Why'd the first solution work? I get what was altered but not how that would change the outcome. Would I then have to change every array inside the loop to [i+1]? Otherwise, wouldn't the arrays[n] be ignored?
As for the second, I guess it has something to do with the order of operations. Would I need to change the ones inside the loop to [i+1] as well or would that break it?
edit: I changed n to 1 on declaration, then i to n-1 and kept i > 0 as opposed to >=, and that seems to have worked.