Finding Max Number in an Array C Programming

前端 未结 4 1570
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 10:21

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)
{
    in         


        
相关标签:
4条回答
  • 2020-12-20 10:56

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

    normally it should be something like

    for (i=0; i<size; i++)
    
    0 讨论(0)
  • 2020-12-20 11:00

    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)
    
    0 讨论(0)
  • 2020-12-20 11:06

    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 讨论(0)
  • 2020-12-20 11:09

    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.

    0 讨论(0)
提交回复
热议问题