0

I'm trying to make a function that identifies the maximum value in an array and calculate the sum of each time it appears. That's fine but the problem is that I need to make the function args the size of the array and the array itself.

This is what I've come up this far:

int sum(int a, int size)
{
    int i, max, output=0;

    //checking every index for max value
    for(i=0;i<=tam;i++){
        if(i==1){
            //setting max on the first index
            max=a[i];
        }else{
            if(a[i]>max){
                a[i]=max;
            }
        }
    }
    //making the sum
    for(i=0;i<size;i++){
        if(a[i]==max);
        output=output+max;
    }
    printf("%d", output);
}

The argument "a" is the array and the size is the size of the array. I get errors saying "a" is neither array nor pointer nor vector.

Any help is apreciated.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
face
  • 3
  • 3
  • 1
    `int a` -> `int *a` – kaylum Jan 20 '21 at 10:34
  • 2
    " I get errors saying "a" is neither array nor pointer nor vector." That would be because `a` is indeed not an array. Seriously, if you can't track down the reason for this compiler error, you need to take a step back and read the array chapter of your C book one more time. – Lundin Jan 20 '21 at 10:45

4 Answers4

1

Replace int sum(int a, int size) to int sum(int *a, int size) or int sum(int a[], int size)

Itati
  • 193
  • 11
1

This function declaration

int sum(int a, int size);

declares a function with two parameters of the type int. If you mean that the first parameter should specify a one-dimensional array then the function declaration will look like

int sum(int a[], int size);

or

int sum( int *a, int size);

because a parameter having an array type is adjusted by the compiler to pointer to the array element type.

Also your function returns nothing though its return type is not void.

Moreover the function uses undeclared variables as for example the variable tam.

And if an array has size elements then the valid range of indices is [0, size ).

Also the function should not change the passed array. And to avoid integer overflow the return type should be long long int.

Also the function should not output any message. It is the caller of the function that decides whether to output a message.

The function can look the following way as it is shown in the demonstrative program below.

#include <stdio.h>

long long int sum( const int a[], size_t n )
{
    long long int total = n == 0 ? 0 : a[0];
    
    size_t max = 0;
    
    for ( size_t i = 1; i < n; i++ )
    {
        if ( a[max] < a[i] )
        {
            total = a[i];
            max = i;
        }
        else if ( !( a[i] < a[max] ) )
        {
            total += a[max];
        }
    }
    
    return total;
}

int main(void) 
{
    int a[] = { 2, 8, 8, 9, 7, 3, 8, 1, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );
    
    printf( "The sum of elements with the maximum value is %lld\n", sum( a, N ) );
    
    return 0;
}

The program output is

The sum of elements with the maximum value is 18
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `int sum(int size, int a[size]);` is also valid and sizeof inside the function will evaluate to the right value at runtime. The only gripe I have with the notation is that the size parameter has to occur before the array parameter, breaking the array, array_size convention – andyn Jan 20 '21 at 10:53
  • @andyn int a*[size] is an invalid declaration. – Vlad from Moscow Jan 20 '21 at 10:55
  • Typo, fixed it. – andyn Jan 20 '21 at 10:56
  • @andyn This declaration int a[size]) also does not allow to get the number of elements in the array using the sizeof operator applied to the variable a. – Vlad from Moscow Jan 20 '21 at 10:58
0
#include<stdio.h>
#include<stdlib.h>
int sum(int *a, int size);
int main()
{
   int *a=(int*)malloc(10*sizeof(int));

    for(int i=0;i<10;i++)
          a[i]=i+1;
          sum(a,10);
 }

int sum(int *a, int size) { int i, max, output=0;

//checking every index for max value
for(i=0;i<size;i++){
    if(i==1){
        //setting max on the first index
        max=a[i];
    }else{
        if(a[i]>max){
            a[i]=max;
        }
    }
}
//making the sum
for(i=0;i<size;i++){
    if(a[i]==max);
    output=output+max;
}
printf("%d", output);

}

0

Well, you can do it in just one pass, as when you identify a new maximum, the accumulated sum of the last is no longer valid (it refers not to the biggest number, but to one smaller)

There's something in your code that is weird... you start the loop at 0, and then compare if (i == 1) which I guess is a mistake (shouldn't it be 0?), as you should want to check if you are at the first (and not at the second cell) to do the initialization of max. Anyway, there's a clever way to do is to initialize max to the minimum number you can have (and for an int you have that value in <limits.h> as the constant INT_MIN). I'll show you now one possible source code to your problem (taken from yours, but changed some variables and added others to show you that in one pass you can do a lot of work:

#include <stdio.h>
#include <limits.h>

/* pretty format of output with location of trace in source file
 */
#define F(_fmt) __FILE__":%d:%s: "_fmt,__LINE__,__func__

/* to pass an array, just declare it as below.  The array size is
 * unspecified because your don't know it before calling sum,
 * and this is the reason to pass the array size. */
int sum(int a[], int size)
{
    int i, pos0 = -1, pos1 = -1, max = INT_MIN, output=0;

    /* checking every index for max value, and output, you made
     * an error here and used tam instead of size. */
    for(i = 0; i <= size; i++){
        if (a[i] > max) {  /* if greater than max */
            pos0 = i;      /* save position as first */
            max = a[i];    /* save max value */
            output = max;  /* initialize output to max */
        } else if (a[i] == max) {  /* if equal to max */
            pos1 = i;      /* save position as last */
            output += max; /* add to output */
        } /* else nothing */
    }
    /* print all the values we got */
    printf(F("pos0 = %d, pos1 = %d, max = %d, output = %d\n"),
        pos0, pos1, max, output);
    return output;         /* return the requested sum */
}

int list[] = { 3, 2, 5, 6, 5, 4, 7, 3, 7, 4, 7, 2, 1, 6, 2 };
            /* max is located    ^     ^     ^  in these positions
             *                   6     8    10   */

/* the following macro gives us the size of the array list by
 * dividing the size of the complete array by the size of the
 * first element. */
#define n_list (sizeof list / sizeof list[0])

int main()
{
    printf(F("result = %d\n"), sum(list, n_list));
}

which should output (if the program is named test from test.c):

$ test
test.c:23:sum: pos0 = 6, pos1 = 10, max = 7, output = 21
test.c:34:main: result = 21
$ _
Luis Colorado
  • 10,974
  • 1
  • 16
  • 31