Reputation: 71
I'm trying to write C code where the user inputs 10 values and the index, and the output should display the index's value from the 10 values set by the user.
The problem statement:
Your grandparents gave you a fantastic cooking recipe but you can never remember how much of each ingredient you have to use! There are 10 ingredients in the recipe and the quantities needed for each of them are given as input (in grams). 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
Example Input:
500 180 650 25 666 42 421 1 370 211
3
My code:
#include <stdio.h>
int main(){
int ingred[9];
int readValue = 0;
int ID;
for(int i = 0; i < 9;i++){
scanf("%d %d", &readValue,&ID);
ingred[i] = readValue;
}
printf("%d",ingred[ID]);
return 0;
}
My output is always 0. Doesn't the scanf() function read the next line of code after the user presses "enter"? Please help.
Upvotes: 0
Views: 800
Reputation: 1
#include <stdio.h>
int main(void){
int i = 0;
int entry;
int index = 0;
int array[10];
for(i = 0; i <10; i++){
scanf("%d", &entry);
array[index] = entry;
index = index + 1;
}
scanf("%d", &index);
printf("%d", array[index]);
return 0;
}
Try this.
Upvotes: 0
Reputation: 83
Is it a requirement to read all of the quantities from a single line? Because that can be a little tricky to perform with scanf. You could iterate trough a loop and get all of the quantities one by one, like this:
#include <stdio.h>
int main ()
{
int ingredients [10];
int newQuantity = 0;
int ingredientId;
int index;
for (index = 0; index < 10; index++)
{
printf ("Enter quantity #%d: ", index);
scanf ("%d", &newQuantity);
ingredients [index] = newQuantity;
}
printf ("Enter the ID: ");
scanf ("%d", &ingredientId);
printf ("Quantity: %d\n", ingredients [ingredientId]);
return 0;
}
On your code you tried to read a pair of integer values nine times in your loop. That's also something to note: despite array indexes beginning at 0, when you declare an array, the value between brackets is the number of elements of the array, not the index of the last element.
Upvotes: 1