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.