I had to make a function that prints out all the numbers in an array (provided in 'main'), within a certain index (eg between 0-11, or 2-6, etc). Then the function has to return the value of the last index value.
For example, given the array
{8, 3, 6, 7, 9, 5, 3, 8, 6, 7, 4, 5}
If I input the numbers 2
and 7
, then it should printf {6 7 9 5 3 8}
, and then return 8. However it keeps returning
6`.
int index(int data[], int low, int high)
{
while(low <= high) {
printf("%d\n", data[low]);
low++;
}
return data[low];
}
/* I know I could just put return[high], but i though it
wouldn't matter since 'low' keeps incrementing until low == high */
int main()
{
int activities[12] = {8, 3, 6, 7, 9, 5, 3, 8, 6, 7, 4, 5};
int low, high;
int x;
printf("What is the starting day? ");
scanf("%d", &low);
printf("What is the ending day? ");
scanf("%d", &high);
x = index(activities, low, high);
printf("\n\nThe function returns this value: %d",x);
return 0;
}
When you return data[low]
, low is already incremented by 1. The last value of low would be high + 1
. The while condition would fail and then come out of the loop.
So, your code should be:
return data[high];
If you want to return the last value using the low
variable you can simply do
return data[--low];
Because while checking the condition it fails when the value of low
is greater than the value of high
.
For example the if you enter low = 2 and high = 7, in the last iteration low become 8 and break the loop which now points to value 6 in activities array since activities[8] == 6
So I would suggest to simply return the value using the last index that is,
return data[high];
Just return data[high]; You incremented low to one after high so it returns that value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.