Trying to find the maximum term in an array using C -
i trying write program can find maximum of array using maxterm function.
basically tell program how many numbers want put in array, put in each number, , tells largest number.
the program works fine arrays of size 4 or smaller arrays longer 4 maxterm returned incorrect: it's large number wasn't part of array.
for example:
please enter number of data values: 4 enter value 1: 1 enter value 2: 3 enter value 3: 4 enter value 4: 1 maximum term 4
but:
please enter number of data values: 5 enter value 1: 1 enter value 2: 3 enter value 3: 8 enter value 4: 4 enter value 5: 2 maximum term 32767
here code:
#include <stdio.h> int maxterm(int *numbers, int *size) { int index = 0; int max = numbers[0]; (index = 0 ; index < *size ; index++) { if (max < numbers[index+1]) { max = numbers[index+1]; } } return max; } int main(int argc, const char * argv[]) { int num, index; printf(" please enter number of data values: "); scanf("%d", &num); //user enters in length of number list int array[num]; (index = 0 ; index < num ; index++) { printf("please enter in value %i: ", (index + 1)); scanf("%i", &array[index]); //list created number number } int maxi = maxterm(array, &num); //the highest number in list determined using maxterm function. printf("the maximum term %i", maxi); return 0; }
where error?
you going out of bounds here:
for (index = 0 ; index < *size ; index++) { if (max < numbers[index+1]) { max = numbers[index+1]; } }
instead iterate normally, except start second element.
Comments
Post a Comment