I may not know C as well as I know C++, but this might help
Firstly, it'll be a little different depending on whether or not you are using C99 or an earlier standard.
For C99
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <stdbool.h> //this gives us access to bool
//skip the code you've already written
bool found = FALSE;
int index = -1;
//if you want to iterate through the array you've made, you must start at index 0, not -1.
//i'm not sure what you want to do with the index variable set to -1.
//if you try to iterate with an index of -1, you will get an out-of-bounds issue
int arrayIndex = 0;
while (arrayIndex <= 9 && found == FALSE)
{
if (item == nums[arrayIndex]
{
found = TRUE;
//arrayIndex will tell us which index it is at
break; //not necessary, as the while loop's condition will fail and the program
// will exit the while loop, but this might help visualize what is going on
}
else
arrayIndex = arrayIndex + 1;
}
location = arrayIndex; //this will be 0 if the first element in the array was the number that
//the user was looking for, so add 1 to this if you want it to show 1 as being the first element
//continue with the rest of your code
|
so, if the user wanted to look for 10, that would be the second element in the array. arrayIndex will equal 1 (since we count from 0 not from 1). You can just add 1 to arrayIndex if you want the user to see "item found at location 2" instead of "item found at location 1".
You could also change the end of your code to this:
1 2 3 4
|
if (found == TRUE)
printf("The item was found at index location %d\n", location);
else
printf("The item was not found in the list\n");
|
If you're not using C99 and don't have access to <stdbool.h>, then replace 'bool' with 'int', and use 0 for FALSE and 1 for TRUE.
Like I said, I don't know C as well as I know C++, so you might want to double-check my syntax for errors. I hope this helps.