开发者

Finding Max Number in an Array C Programming

I am trying to find the max number in an array. I have created a function and I am using the following code:

int maxValue( int myArray [], int size)
{
    int i, maxValue;
    maxValue=myArray[0];

    //find the largest no
    for (i=0;i)
        {
        if (myArray[i]>maxValue)
        maxValue=myArray[i];
        }   
        return maxValue;
}

However I get a syntax error before ) token. What am I doing wrong a开发者_如何学Pythonnd am I even doing this right? Any help would be greatly appreciated.


You must pass a valid array with at least one member to this function:

#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int
maxValue(int myArray[], size_t size) {
    /* enforce the contract */
    assert(myArray && size);
    size_t i;
    int maxValue = myArray[0];

    for (i = 1; i < size; ++i) {
        if ( myArray[i] > maxValue ) {
            maxValue = myArray[i];
        }
    }
    return maxValue;
}

int
main(void) {
    int i;
    int x[] = {1, 2, 3, 4, 5};
    int *y = malloc(10 * sizeof(*y));

    srand(time(NULL));

    for (i = 0; i < 10; ++i) {
        y[i] = rand();
    }

    printf("Max of x is %d\n", maxValue(x, sizeof(x)/sizeof(x[0])));
    printf("Max of y is %d\n", maxValue(y, 10));

    return 0;
}

By definition, the size of an array cannot be negative. The appropriate variable for array sizes in C is size_t, use it.

Your for loop can start with the second element of the array, because you have already initialized maxValue with the first element.


A for loop has three parts:

for (initializer; should-continue; next-step)

A for loop is equivalent to:

initializer;
while (should-continue)
{
    /* body of the for */
    next-step;
}

So the correct code is:

for (i = 0; i < size; ++i)


the paren after the for seems to be missing some contents.

normally it should be something like

for (i=0; i<size; i++)


include:

void main()
{
  int a[50], size, v, bigv;
  printf("\nEnter %d elements in to the array: ");

  for (v=0; v<10; v++)
    scanf("%d", &a[v]);

  bigv = a[0];

  for (v=1; v<10; v++)
  {
    if(bigv < a[v])
      bigv = a[v];
  }

  printf("\nBiggest: %d", bigv);
  getch();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜