Thursday, July 30, 2009

C programming newbie: How to store a new value with each loop?

I need a program that stores a new value each time it goes through a loop. I have this code:


for (s =1; s%26lt;= products; s++)





{





printf("State the price:");


scanf("%i", %26amp;price);





}





Obviously it won't work because each time it goes through the loop, it will overwrite the previous value. How can I store every value the user inputs without overwriting the previous one?

C programming newbie: How to store a new value with each loop?
int userinput[products];


for (s =0; s%26lt;= products; s++)





{





printf("State the price:");


scanf("%i", %26amp;price);


userinput[s] = price;


}
Reply:You need to create an array and each time it goes through the array it changes the index of the array like this





int pr[products];





for(s=1; s%26lt;= products; s++)


{


pr[s] = price;


printf("State the price")


scanf("%i", %26amp;pr[s]);


}





--


the array pr will hold all the values of the products and can be used whenever you want.
Reply:store them in an array, instead of using "price" use price[s], this of course will need to be declared as an array first. Then each time you loop it will get stored in the array price[0], price[1], price[2], etc.
Reply:use an array





int arr[100];


for (s =0; s%26lt; products; s++)





{





printf("State the price:");


scanf("%d", %26amp;arr[i]);





}





this one will store each value in


arr[0]


the next one in arr[1]


and so on





REASONS


i changed the for loop from 1 to 0 as arrays start from 0 and it doenst disturb the loop since i made it to 0 to products -1


and i changed %i to %d coz i think d is the right for intiger


i dont know about i and i havnt tried that

buy flowers

No comments:

Post a Comment