There are multiple reasons for your program to fail:
the definition int array[a] = {};
uses an uninitialized variable a
, so the program has undefined behavior. You must define this array after reading the value of a
.
variable sized automatic arrays cannot have an initializer. You must initialize the array some other way, or not at all since you read the values in the following loop.
if the size a
is negative or too large, the creation of the local array will have undefined behavior. Allocating from the heap with malloc()
or calloc()
is preferable for potentially large objects.
you do not test the return value of scanf()
, causing undefined behavior on invalid input.
Here is a corrected version:
#include <stdio.h>
int main() {
int sum;
int a;
printf("Insert length of array:\n");
if (scanf("%d", &a) != 1 || a <= 0 || a > 1000) {
fprintf(stderr, "Invalid input\n");
return 1;
}
int array[a];
for (int i = 0; i < a; i++) {
printf("Insert number %d:\n", i + 1);
if (scanf("%d", &array[i]) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
}
sum = 0;
for (int i = 0; i < a; i++) {
sum = sum + array[i];
}
printf("Sum is %d\n", sum);
return 0;
}
If you want to handle larger arrays, you can allocate the array with malloc()
, but you can also just compute the sum on the fly and not store the values read in an array:
#include <stdio.h>
int main() {
int a, value, sum;
printf("Insert length of array:\n");
if (scanf("%d", &a) != 1 || a < 0) {
fprintf(stderr, "Invalid input\n");
return 1;
}
sum = 0;
for (int i = 0; i < a; i++) {
printf("Insert number %d:\n", i + 1);
if (scanf("%d", &value) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
sum += value;
}
printf("Sum is %d\n", sum);
return 0;
}