Consider your code:
int n,a[n],op;
Given that the value of n
is undefined at this point, the variable length array (VLA) created by a[n]
will be of some arbitrary size. C doesn't magically reach back in time from the point where you request a value of n
and adjust the array size :-)
You need to create the VLA after you've set the value of n
, reorganising your code at the start of main
with something like this:
int n,op;
printf("Enter size of the array\n");
scanf("%d",&n);
int a[n];
That way, n
will be a known value when you use it to create the VLA.
Additionally, your scanf("%d",&a[n]);
is undefined behaviour because n
will always be beyond the end of the array (which has indexes 0
through n-1
inclusive). You should be using i
as the index there.
There are other logic issues such as checking that the scanf
succeeded and that you didn't enter a non-positive number but that's usually okay for educational code (assuming that's what this is). As you develop as a coder, you will naturally begin to think of these possibilities and harden your code accordingly.
By way of example, this is a better way to enter n
, although you could recover from non-numeric data as an optional extra (see here for a nifty line input solution in C):
int n = -1;
while (n < 1) {
printf("Enter array size (positive integer): ");
if (scanf("%d", &n) != 1) {
puts("\nERROR: non-numeric");
exit(1);
}
}