I created a program to calculate the sum of 4 array elements. Is it possible to prompt the user to fill array elements manually during program execution and then show the sum? I can do this while not using the function, but I get stuck when I use functions. Is it still possible to do so?
If I insert a for loop inside the main function, just after variable initialization,
int data[];
int total;
int size = sizeof(data) / sizeof(data[0]);
printf("Enter array elements: ");
for(int i=0; i<size; i++) {
scanf("%d", &data[i]);
}
the compiler complains:
error: definition of the variable with array type needs an explicit size or an initializer
int data[];
^
1 error generated.
My program looks like this:
#include <stdio.h>
int sum(int data[], int size)
{
int sum = 0;
int i;
for (i = 0; i < size; i++)
sum += data[i];
return sum;
}
int main()
{
int data[] = { 1, 2, 3, 4 }; // I want user input here
int total;
int size = sizeof(data) / sizeof(data[0]);
total = sum(data, size);
printf("Sum is: %d\n", total);
return 0;
}