3

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.

3
  • 4
    Hint: what you're doing there isn't initializing, it's assignment. Initialization can only occur once, while repeated assignment will change a value over and over. If you keep assigning 0 to a variable, you overwrite whatever value it had before. Commented Feb 10, 2014 at 7:10
  • Try to run the code in your head. It's simple enough that you should be able to. Then fire up a debugger and single-step through it and compare your expectation with the outcome. Commented Feb 10, 2014 at 8:18
  • I am being picky, but the return value from scanf should be checked. Commented Feb 10, 2014 at 9:08

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For completeness, local static variables (e.g. inside main) are initialized at program start up.
1

Answer for your question that is why your program works differently if you initialized "triangulerNumber=0" in second for loop is: If you initialized triangularNumber=0 in second for loop then it will become zero in every iteration of the second for loop and your answer will be only "number" because:

triangularNumber=0;
triangularNumber=triangularNumber+n;

but at last iteration n=number.So i think it is clear now why can't you initialized triangularNumber in second for loop . If any problem you can ask.....

1 Comment

This is the answer I was looking for. You are absolutely right. Everytime it runs the second loop, it resets triangularNumber to 0. That is why the code was not working.
1

Let's walk through your program:

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

create pointers to n, number, counter, triangularNumber. Now somewhere in the memory, there is room to store the values of these ints. This somewhere has not been cleaned.

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 at the adress where triangularNumber points to is changed to hold a value, value 0.

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

If you would not have set triangularNumber to 0 at 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 needed, the reference to these adresses is discarded anyway and the memory is free for other stuff to be used.

}

return 0;

}

1 Comment

Thanks! This is a great step-by-step explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.