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

I am looking at a C programming book, and I have a question why a piece of code depends on when I initialize the 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 on line 12, I initialized the triangularNumber = 0 variable before the second loop.

That I cannot understand why the program fails when I initialize triangularNumber = 0 in the second loop, for example, on line 17. I do not understand why the program acts differently and was hoping to get a better understanding of what happens by asking question.

+3
source share
3 answers

, -, "triangulerNumber = 0" : triangularNumber = 0 , , "", :

triangularNumber=0;
triangularNumber=triangularNumber+n;

, , n = number.So, , , triangularNumber . , .....

+1

, , , . (.. main()), . , , , , .

, 12 , , , .

-, 12 , , reset n 0, .

+2

:

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

n, , , . - int. - .

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.

Now for the first time, the memory in the address where the triangular number indicates indicates the value, the value is 0.

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

If you had not set triangularNumber to 0 on line 12, the first time through this loop, triangularNumber would have an unknown value.

    }

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

not required, a link to these addresses is discarded anyway, and memory is free for other things to be used.

}

return 0;

}

+1
source

All Articles