Reputation: 29
I'm making a program that will let me read an integer entered at the terminal via the scanf
function, and generate its assigned value from the array that has been created already. Here is the program's description:
Your program must read 10 integers (the quantities needed for each of the ingredients, in order) and store them in an array. It should then read an integer which represents an ingredient's ID number (between 0 and 9), and output the corresponding quantity.
#include <stdio.h>
int main () {
int array[10];
int store = 0;
int i = 0;
printf("write how much the ingredients weigh in grams\n");
for (i=0; i<10; i++) {
scanf("%d", array);
printf("%i weighs %dg\n", i, array[store]);
}
printf("Which ingredient ID do you want to check the weight of? ");
int ingredient = 0;
scanf("%d", &store);
printf("The weight of this ingredient is: %d\n", ingredient[array]);
}
For example, if the values stored in the array are: 23, 54, 12, 51, 11, 10, 99, 32, 9, 14 then I would expect the program to print '12' when I type '2' after being prompted with the question "Which ingredient id do you want to check the weight of?" However, at the moment when I type the number '6' for example, it will generate the value assigned to the number '8'. So it will generate '9' instead of '99'.
How can I fix this?
Upvotes: 1
Views: 46
Reputation: 16876
This here is wrong:
scanf("%d", array);
It stores the read in value in the first element. Since it stores them all there, it just overwrites it all the time, resulting with your last value in array[0]
and the rest is uninitialized. Do this instead:
scanf("%d", &array[i]);
The same goes for the debugging print, it should be:
printf("%i weighs %dg\n", i, array[i]);
Also, there's a problem here:
printf("The weight of this ingredient is: %d\n", ingredient[array]);
ingredient[array]
is array[ingredient]
(explanation here), but ingredient
is always 0
because you don't change it. Hence it's always reading that first element of the array (the element that you set last, due to the other issue). Do array[store]
instead. You can remove the ingredient
variable, it's unneeded.
Upvotes: 4