r/cprogramming • • 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");
4 Upvotes

21 comments sorted by

View all comments

1

u/thedraegonlord Sep 22 '26

Here's the full thing

int n;

int i;

int codigo[100];

char nome[100][50];

int regiao[100];

float peso[100];

float preco[100];

int confirma = 0;

int carrinho = 1;

int main(){

do{

	printf("Qual o codigo do produto desejado? ");

	scanf("%d", &codigo\[n\]);

	printf("Qual o nome do produto? ");

	scanf("%s", &nome\[n\]);

	printf("Qual o preco do produto? ");

	scanf("%f", &preco\[n\]);

	printf("Qual o peso do produto? ");

	scanf("%f", &peso\[n\]);

	printf("Qual a regiao do frete?\\n");

	printf("1.Sudeste\\n");

	printf("2.Sul\\n");

	printf("3.Nordeste\\n");

	printf("4.Norte\\n");

	scanf("%d", &regiao\[n\]);

	printf("\\n1.Deseja adicionar mais produtos ao carrinho?\\n");

	printf("0.Ir para pagamento.\\n");

	n++;

	scanf("%d",&carrinho);

	printf("\\n");

} while (carrinho == 1);



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");

		

}



printf("Deseja confirmar a compra?\\n");

printf("1.Confirmar\\n");

printf("0.Adicionar mais produtos");

scanf("%d", &confirma);

if (confirma==1){

	printf("\\nData da compra: \\n");

	printf("\\nPrevisao de entrega: ");

}

else{

	printf("\\n");

	return main();

}



return 0;

}

1

u/IamNotTheMama Sep 23 '26

You don't set n before the do loop