0

I am a bit of a noob in programming, that is why I am struggling with this rather simple code. Our task is to sum up all elements of an array using a function. The function should print out the array, then sum up its elements and give back its sum to the main. There it should be printed. It is working until it gets to the function, I think.

Read a lot of other posts regarding this question but still can't wrap my head around the solution. My compiler is also telling me "Segementation fault (core dumped)". I am really confused.

That's my code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 9           // i think the math one is a bit unneccessary but well

int sum(int array[], int size)
{
    int i;
    int sum = 0;
    for (i = 0; i <= MAX; i++)
    {
        printf("\n%d", array[i]);
    }
    for (i = 0; i <= MAX; i++)
    {
        sum = sum + array[i];
    }
    return sum;
}

int main()
{
    int i;
    int array[MAX];
    int size;
    for (i = 1; i <= 10; i++)
    {
        printf("\nGeben Sie die %d. Zahl ein: ", i);      // Its in german, basically saying the user should fill the array, starting with the 1. element
        scanf("%d", &array[i - 1]);
    }
    sum(array[MAX], size);
    printf("%d", size);
    return 0;
}

Helping me would be really nice. Thanks!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
sam3004
  • 11
  • 2
  • If you have an array with MAX elements then valid indices are 0 - MAX-1. – Vlad from Moscow Dec 29 '20 at 22:11
  • `for (i = 1; i <= 10; i++)` -> `for (i = 1; i <= 9; i++)`. Better still use more standard 0 based counter: `for (i = 0; i < MAX; i++) scanf("%d", &array[i]);` – kaylum Dec 29 '20 at 22:12
  • @sam3004 Your function does not use the parameter size and the passed argument size is not initialized. – Vlad from Moscow Dec 29 '20 at 22:13
  • 1
    `sum(array[MAX], size);` -> `sum(array, size);`. The compiler should give you a warning about that as the types are incompatible. Always take note of the warnings. – kaylum Dec 29 '20 at 22:13

4 Answers4

2

That happens because array elements go from 0 to MAX - 1. By looping from 0 to MAX (included) you're asking your program to access up to the 11th element (array[10]).

Bonus: your call to the function should be sum(array, size) and you could use a single loop instead of two:

for (i = 0; i < MAX; i++)
{
    printf("\n%d", array[i]);
    sum = sum + array[i]; // Same as sum += array[i];
}

<math.h> is indeed unnecessary here and you didn't use <stdlib.h> nor the parameter size, so you can safely remove them.

MDXZ
  • 160
  • 12
  • I was worrying about `size` not being initialised, without noticing that it is ignored, well spotted. (Strictly it still is undefined behaviour I think.) – Yunnosch Dec 29 '20 at 22:57
1

If you have an array with MAX elements then the valid range of indices is [ 0, MAX ).

The function sum does not use the parameter size and the passed argument size was not initialized.

Moreover the first parameter of the function call

sum(array[MAX], size);

has the type int instead of int *.

The program can look the following way

#include <stdio.h>

#define MAX 9

long long int sum( const int array[], size_t size )
{
    long long int total = 0;

    for ( size_t i = 0; i < size; i++ )
    {
        total += array[i];
        printf( "%d ", array[i] );
    }
    
    putchar( '\n' );
    
    return total;
}

int main(void) 
{
    int array[MAX];
    
    for ( size_t i = 0; i < MAX; i++ )
    {
        printf("Geben Sie die %zu. Zahl ein: ", i + 1 );
        scanf( "%d", array + i );
    }
    
    printf( "%lld\n", sum( array, MAX ) );
    
    return 0;
}

Its output might look like

Geben Sie die 1. Zahl ein: 1
Geben Sie die 2. Zahl ein: 2
Geben Sie die 3. Zahl ein: 3
Geben Sie die 4. Zahl ein: 4
Geben Sie die 5. Zahl ein: 5
Geben Sie die 6. Zahl ein: 6
Geben Sie die 7. Zahl ein: 7
Geben Sie die 8. Zahl ein: 8
Geben Sie die 9. Zahl ein: 9
1 2 3 4 5 6 7 8 9 
45
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

I use a function sum to scan the elements of the array and I summed the elements of array

    scanf("%d", &array[i - 1]);

if You want to fill the array from the SIZE-1 to 0 ,just reverse the for loop (for(int i=SIZE-1;i>=0;i--))

  int size;

If you want to make size as argument when you called your function ,you should initialized it at SIZE(size=SIZE)

your function sum returned the sum of elemnts of array, so changed this

sum(array[MAX], size);//use it in void main()

to

 int k = sum(array, size);//just write the name of array without [MAX]

My code :

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 9           // i think the math one is a bit unneccessary but well

int sum(int array[], int size)
{
  int sum = 0;
  for (int i = 0; i < MAX; i++)
  {
    scanf("%d",&array[i]);
    sum = sum + array[i];
  }
  return sum;
}

 int main()
{
  int array[MAX];
  printf("%d",sum(array, MAX));//here you just write the name of array without his size
  return 0;
}
MED LDN
  • 684
  • 1
  • 5
  • 10
  • Sorry, I was writing my answer and I didn't see that you posted yours in the meantime. What is the code of conduct in this case, shall I delete mine since they're quite similar? – MDXZ Dec 29 '20 at 22:21
  • 3
    @MDXZ: If you think that your answer adds no value to a previous one, you can delete it. But this one is a code only answer, while yours contains explainations, so my advice is that you should keep it. – Serge Ballesta Dec 29 '20 at 22:26
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Dec 29 '20 at 22:57
  • Sorry a lot , I make the explanations – MED LDN Dec 29 '20 at 23:10
  • Thanks for your fast replies guys! Your answers helped me a lot! – sam3004 Dec 31 '20 at 16:52
0

You need to have it clear in mind that the last element of an array declared with MAX elements is the MAX-1-th because elements start from 0.

For example, the elements of int array[3] are: array[0], array[1] and array[2].

Now you understand that your loops should be

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

Because in case of i == MAX you would try to access array[MAX] which is not part of your array.

If MAX is 9, the last element is array[8] so for (i = 0; i <= 10; i++) should be

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

But it's better to use MAX instead of 9, so that if you want to make your program to work for an array of 20 elements you have to modify only the value of MAX and not all the piece of code where you wrote 9

Now coming to the function call sum(array[MAX], size); it should be

sum(array, size);

To pass an array you have to pass the address of its first element, that is &array[0] or even just array. Is an array name a pointer?

Then the size you passed is uninitialised and you don't even use it in sum(), so there's no no reason to declare it.

Also I noticed that you wanted to print size at the end and since you passed it to sum(), maybe you wanted to modify its value into the sum() function. If that's the case, then simply passing size is not enough. This would pass a copy of size and any change to its value would be lost (unless you return it, but you are already returning sum). To really modify size you have to pass its address &size, and have sum() receiving a pointer to int int *

int sum(int array[], int *size)

And also you return sum but don't store it anywhere. You should store it somewhere like

newVariable = sum(array, size);

Or if you just want to print it, then just print it

printf("%d", sum(array, size));
anotherOne
  • 1,513
  • 11
  • 20