Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following code depend on when I initialize the variable?

I am going through a C Programming book, and I have a question about why a snippet of code depends on when I initialize a variable.

The code can be found here: http://paste.ubuntu.com/6907608/

#include <stdio.h>

int main(void)
{
    int n, number, counter, triangularNumber;

    for(counter = 1; counter <= 5; ++counter)
    {
        printf("What triangular number do you want? ");
        scanf("%i", &number);

        triangularNumber = 0; // Line 12: I was having a hard time with this program because
                              // I kept forgetting to initialize triangularNumber to 0.

        for(n = 1; n <= number; ++n)
        {
            triangularNumber += n;
        }

        printf("Triangular number %i is %i\n\n", number, triangularNumber);
        n = 0;
        triangularNumber = 0;
    }

    return 0;
}

As you can see in line 12, I initialized the variable triangularNumber = 0 before the second for loop.

What I can't get my head around is why the program fails when I initialize triangularNumber = 0 inside the second for loop, say in line 17. I don't understand why the program acts differently and was hoping to get a better understanding of what is going on by asking the question.

like image 342
user3237895 Avatar asked Jun 27 '26 18:06

user3237895


1 Answers

The thing tripping you up appears to be how variables are initialised. When you declare a global variable (i.e. outside main()), it's initialised to zero. When you declare a local variable, as you've done here, it's not initialised at all, so it starts with some unknown number until you set it to a value.

So without line 12, the first iteration through your outer loop is working with an unknown value in triangularNumber, and presumably you saw garbage output.

If anything, your line 12 is right, and the lines at the end of the outer loop, to reset n and triangularNumber to 0, are superfluous.

like image 60
John Bickers Avatar answered Jul 03 '26 13:07

John Bickers