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!
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));