So I was following along the week one lecture, and I was trying to replicate the average-taking program, when I made a slightly silly mistake- I used the average function within the for loop.

#include <stdio.h>
#include <cs50.h>
//placeholder var to display some random value; for testing purposes
const char placeholder = 'x';

//to alert about the function
float average(int length, int arbitraryarray[]);

//main code
int main(void)
    int size = get_int("number of scores you want to input: ");
    int scores[size];
    for(int i = 0; i < size; i++)
        scores[i] = get_int("Score number %i: ", i + 1);
        printf("your average value is: %f\n", average(size, scores));

//function to take average
float average(int length, int arbitraryarray[])
    int sum = 0;
    for(int j = 0; j < length; j++)
        //add everything in the scores array
        sum += arbitraryarray[j];
    //average calculation
    return (float) sum/ (float)length;

The obvious mistake, is as you can see, the location of the printf block, and the average function. And it doesn't detract from the program. But when I ran it, I noted that the following output was retreived-

enter image description here

On typing in 100 the first time, I received an output value of 16432.5 . When I added the second value, it functions like normal, which which I understand. However, I can't seem to understand how 16432.5 came about- if anything, shouldn't the value be 50? So I repeated the function again, just for fun, and noted that it went down by .5- becoming 16432.

I repeated with some arbitrarily high values, and the initial number of 16300-16400 keeps on varying, and I'm very curious to know what exactly is happening over here.

enter image description here

Picture of the arbitrary values I tried afterwards.

Any help would be appreciated.

1 Answer 1


Local variables are not initialised by default. The values you find there are the remains of other variables (or data related to function calls) that occupied that exact same location of the stack previously, for example as part of a get_int or printf call. It's your responsibility to assign a value before you read it. Often that means to initialise the variable properly, here the mistake was reading before it got its values.

Global variables, however, are always initialised, if you don't specify a value, they are implicitly initialised to all bytes zero.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .