n350xwb
n350xwb

Reputation: 3

Elements in my array are storing incorrect values even after user is being prompted

I'm trying to create a score storing program where I ask a user for scores to store in an array and just print them out at the end of it. However, when I tried to do that, the values of the array are being changed to 32764, 4198754 etc.

My code:

int main (void){
    int score;
    //int sum = 0;
    int num_score = get_int("Enter the number of scores: ");
    int scores[num_score]; 
    printf("Enter Scores below\n");
    for (int i = 1; i <= num_score; i++){
        score = get_int("Score %i: " ,i); 
        score = scores[i]; 
        }
        printf("The scores are as follows: \n");
        for (int i = 1; i <= num_score; i++ ){
        //sum = sum + scores[i];
        printf("Score %i = %i\n",i,scores[i]);
        }
 

For example, if there are a total of 3 scores, and the user enters score 1 = 78, score 2 = 67 and score 3 = 83 The expected output should be:

Score 1 = 78
Score 2 = 67
Score 3 = 83

Instead, the values that were printed out are as follows:

Score 1 = 32767
Score 2 = 4198754
Score 3 = 0

Why is this so? I'd like to understand see where I went wrong.

Upvotes: 0

Views: 89

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You misused the assignment operator here:

score = scores[i]; 

The assignment operator sets the value of lefthand operand to the value of righthand operand.

It should be:

scores[i] = score;

Also the array declaration

int scores[num_score];

should be

int scores[num_score+1];

To enable usage of scores[num_score].

Upvotes: 2

Related Questions