# runtime error in sandbox for array examples from week 2 lecture

This is confusing me a little and I want to fully understand it before moving through the rest of the lecture. I usually code alongside David's examples on screen and was trying to understand why this makes sense

``````#include <cs50.h>
#include <stdio.h>

int main(void)
{
int n = get_int("Number of scores: ");
int scores[n];
for(int i = 0; i < n; i++)
{
scores[i] = get_int("Score %i: ", i + 1);
}

printf("Average: TO DO\n");
}
``````

and yet this doesn't (and also produces a run-time error in sandbox):

``````#include <cs50.h>
#include <stdio.h>

int main(void)
{
int n = get_int("Number of scores: ");
int scores[n];
for(int i = 0; i < n; i++)
{
scores[n] = get_int("Score %i: ", i + 1);
}

printf("Average: TO DO\n");
}
``````

The error I got was

``````runtime error: index 3 out of bounds for type 'int [n]'
``````

I'm confused as to why the one in the loop can't be n? I can't even begin to describe my logic on this...

When the int array `scores` is declared here `int scores[n];` it will have n elements, indexed to 0. When 3 is entered, the elements of scores are `scores`, `scores` and `scores`. There is no `scores`. (Notice the loop executes until `i < n` to ensure it will be within bounds). This line `scores[n] = get_int("Score %i: ", i + 1);` will try to populate `scores`, which produces the "out of bounds" error.
• "why was n stored in an array": n is not in an array; its only purpose is to define the length of the array (`int scores[n];`). The loop needs to be limited to the array size so as not to provoke an "out of bounds error". Dec 17 '20 at 18:54